ARKit和SceneKit的一些代码片段(备忘)

工具类头部声明,其他一些启动方法等忽略

@interface XWAIARCamera ()<ARSCNViewDelegate>
/// AR场景配置
@property (nonatomic, strong) ARWorldTrackingConfiguration *configuration;
/// AR场景会话
@property (nonatomic, strong) ARSession *session;
/// AR场景view
@property (nonatomic, readwrite, strong) ARSCNView *sceneView;
/// 中心点图标:
@property (nonatomic, strong) UIImageView *targetImageView;
/// 父亲视图
@property (nonatomic, weak) UIView *sceneViewSuperView;
/// 距离测量所有线条节点元素
@property (nonatomic, strong) NSMutableArray<ARMeasureElement *> *elementList;
/// 当前震动的节点
@property (nonatomic, strong) SCNNode *shakeNode;
@end

API_AVAILABLE(ios(13.0))
@interface XWAIARCamera ()<ARCoachingOverlayViewDelegate>
/// AR指示器
@property (nonatomic, strong) ARCoachingOverlayView *coachingOverlay;
@end
  1. 在检测到的水平面上面新增一个水平面
- (void)goodAddBoxPlane {
    NSArray<ARHitTestResult *> *results = [self.sceneView hitTest:CGPointMake(CGRectGetWidth(self.sceneView.frame)/2.0, CGRectGetHeight(self.sceneView.frame)/2.0) types:ARHitTestResultTypeExistingPlane];
//    NSLog(@"results: %@",results);
    if(results && results.count > 0) {
        ARHitTestResult *result = results.firstObject;
        NSLog(@"找到锚点: %@",result.anchor);
        
        simd_float4x4 transform = result.worldTransform;
        SCNVector3 worldPosition = SCNVector3Make(transform.columns[3].x, transform.columns[3].y, transform.columns[3].z);
        NSLog(@"\nx:%f \n y:%f \n z:%f\n",worldPosition.x,worldPosition.y,worldPosition.z);
        
        if ([result.anchor isKindOfClass:[ARPlaneAnchor class]]) {
            ARPlaneAnchor *findPlaneAnchor = (ARPlaneAnchor *)result.anchor;
            NSLog(@"extentX:%f extentY:%f extentZ:%f",findPlaneAnchor.extent.x,findPlaneAnchor.extent.y,findPlaneAnchor.extent.z);
            NSLog(@"centerX:%f centerY:%f centerZ:%f",findPlaneAnchor.center.x,findPlaneAnchor.center.y,findPlaneAnchor.center.z);
            SCNNode *node = [self.sceneView nodeForAnchor:findPlaneAnchor];
            
            SCNBox *plane = [SCNBox boxWithWidth:findPlaneAnchor.extent.x height:0.0 length:findPlaneAnchor.extent.z chamferRadius:0];
            plane.firstMaterial.writesToDepthBuffer = NO;
            plane.firstMaterial.diffuse.contents = [UIColor xwai_randomColor];
            SCNNode *planeNode = [SCNNode nodeWithGeometry:plane];
            planeNode.position = SCNVector3Make(findPlaneAnchor.center.x, 0, findPlaneAnchor.center.z);
           
            [node addChildNode:planeNode];
        
        }
    }
}
  1. 新增一个垂直平面
- (void)addSCNPlane {
    matrix_float4x4 translation = matrix_identity_float4x4;
    translation.columns[3].z = -0.2;
//    translation.columns[3].y = -0.1;
    matrix_float4x4 transform = matrix_multiply(self.session.currentFrame.camera.transform, translation);
    SCNVector3 position = SCNVector3Make(transform.columns[3].x, transform.columns[3].y, transform.columns[3].z);
    
    SCNPlane *plane = [SCNPlane planeWithWidth:0.05 height:0.05];
    plane.firstMaterial.diffuse.contents = [UIColor greenColor];
    plane.firstMaterial.lightingModelName = SCNLightingModelConstant;
    plane.firstMaterial.doubleSided = YES;
    SCNNode *geoNode = [SCNNode nodeWithGeometry:plane];
    geoNode.position = position; // SCNVector3Make(0, 0, -0.5);
    [self.sceneView.scene.rootNode addChildNode:geoNode];
    [geoNode runAction:[SCNAction repeatActionForever:[SCNAction rotateByX:0 y:0 z:2 duration:1]]];
}
  1. 新增一个球体
- (void)addBall {
    NSArray<ARHitTestResult *> *results = [self.sceneView hitTest:CGPointMake(CGRectGetWidth(self.sceneView.frame)/2.0, CGRectGetHeight(self.sceneView.frame)/2.0) types:ARHitTestResultTypeExistingPlane];
    if(results && results.count > 0) {
        ARHitTestResult *result = results.firstObject;
        //        NSLog(@"平面距离:%f",result.distance);
        simd_float4x4 transform = result.worldTransform;
        SCNVector3 worldPosition = SCNVector3Make(transform.columns[3].x, transform.columns[3].y, transform.columns[3].z);
        NSLog(@"x:%f \n y:%f \n z:%f\n",worldPosition.x,worldPosition.y,worldPosition.z);
        
        SCNSphere *dot = [SCNSphere sphereWithRadius:0.75]; // 0.5
        dot.firstMaterial.diffuse.contents = [UIColor redColor];
        dot.firstMaterial.lightingModelName = SCNLightingModelConstant;
        dot.firstMaterial.doubleSided = YES;
        
        SCNNode *startNode = [SCNNode nodeWithGeometry:dot];
        startNode.scale = SCNVector3Make(1/300.0, 1/300.0, 1/300.0);
        startNode.position = worldPosition;
        [self.sceneView.scene.rootNode addChildNode:startNode];
    }
}
  1. 新增一个自定义贝塞尔曲线绘制的立体形状
- (void)addCustomShapeByCurrentFrame {
    matrix_float4x4 translation = matrix_identity_float4x4;
    translation.columns[3].z = -0.3;
    matrix_float4x4 transform = matrix_multiply(self.session.currentFrame.camera.transform, translation);
    SCNVector3 position = SCNVector3Make(transform.columns[3].x, transform.columns[3].y, transform.columns[3].z);
    
    SCNPlane *plane = [SCNPlane planeWithWidth:0.05 height:0.05];
    plane.firstMaterial.diffuse.contents = [UIColor greenColor];
    plane.firstMaterial.lightingModelName = SCNLightingModelConstant;
    plane.firstMaterial.doubleSided = YES;
    
    SCNSphere *dot = [SCNSphere sphereWithRadius:0.05]; // 0.5
    dot.firstMaterial.diffuse.contents = [UIColor redColor];
    dot.firstMaterial.lightingModelName = SCNLightingModelConstant;
    dot.firstMaterial.doubleSided = YES;
    
    
    UIBezierPath *bezierPath = [self getBezierPath];
    
//    UIBezierPath *piePiece = [UIBezierPath bezierPath];
//    [piePiece addArcWithCenter:CGPointZero radius:0.0750 startAngle:0.0 endAngle:M_PI/6 clockwise:YES];
//    [piePiece closePath];
//    bezierPath = piePiece;
    
    SCNShape *customShape = [SCNShape shapeWithPath:bezierPath extrusionDepth:0.01];
//    customShape.chamferRadius = 0.2;
//    customShape.chamferMode = SCNChamferModeBoth;
    customShape.firstMaterial.diffuse.contents = [UIColor xwai_randomColorWithoutAlpha];
    customShape.firstMaterial.lightingModelName = SCNLightingModelConstant;
    customShape.firstMaterial.doubleSided = YES;
    // shapeNode.eulerAngles = SCNVector3Make(0,-M_PI_2/6, 0);
    
    SCNNode *geoNode = [SCNNode nodeWithGeometry:customShape];
//    geoNode.eulerAngles = SCNVector3Make(0, 0, M_PI);
    geoNode.position = position;
    [self.sceneView.scene.rootNode addChildNode:geoNode];
//    [geoNode runAction:[SCNAction repeatActionForever:[SCNAction rotateByX:0 y:0 z:2 duration:1]]];
}

- (UIBezierPath *)getBezierPathFrom3DPointList:(NSArray<NSValue *> *)nodeArray {
    UIBezierPath *path = [UIBezierPath new];
    for (int i = 0; i < nodeArray.count; i++) {
        SCNVector3 node = nodeArray[i].SCNVector3Value;
        CGPoint tempPoint = CGPointMake(node.x, node.z);
        if(i == 0) {
            [path moveToPoint:tempPoint];
        } else {
            [path addLineToPoint:tempPoint];
        }
    }
    [path closePath];
    return path;
}

- (UIBezierPath *)getBezierPath {
    /*
    CGPoint firstPoint = CGPointMake(0.10, 0.10);
    CGPoint secondPoint = CGPointMake(0.20, 0.10);
    CGPoint thridPoint = CGPointMake(0.20, 0.15);
    CGPoint fourthPoint = CGPointMake(0.15, 0.15);
    CGPoint fifthPoint = CGPointMake(0.15, 0.20);
    CGPoint sixthPoint = CGPointMake(0.10, 0.20);
    
    NSArray *pointArray = @[
        NSStringFromCGPoint(firstPoint),
        NSStringFromCGPoint(secondPoint),
        NSStringFromCGPoint(thridPoint),
        NSStringFromCGPoint(fourthPoint),
        NSStringFromCGPoint(fifthPoint),
        NSStringFromCGPoint(sixthPoint)
      ];
    //*/
    
    //*/
    CGPoint firstPoint = CGPointMake(0.00, 0.00);
    CGPoint secondPoint = CGPointMake(0.10, 0.05);
    CGPoint thridPoint = CGPointMake(0.05, 0.10);
    CGPoint fourthPoint = CGPointMake(0.00, 0.00);
    
    NSArray *pointArray = @[
        NSStringFromCGPoint(firstPoint),
        NSStringFromCGPoint(secondPoint),
        NSStringFromCGPoint(thridPoint),
        NSStringFromCGPoint(fourthPoint)
      ];
    //*/
    
    UIBezierPath *path = [UIBezierPath new];
    for (int i = 0; i < pointArray.count; i++) {
        CGPoint tempPoint = CGPointFromString(pointArray[i]);
        if(i == 0) {
            [path moveToPoint:tempPoint];
        } else {
            [path addLineToPoint:tempPoint];
        }
    }
    [path closePath];
    return path;
}
  1. 通过遍历寻找场景的平面新增水平面
- (void)addPlaneByForinSceneView {
    NSLog(@"%@",self.sceneView.scene.rootNode.childNodes);
    ARPlaneAnchor *findPlaneAnchor = nil;
    for (SCNNode *node in self.sceneView.scene.rootNode.childNodes) {
        NSLog(@"%@",[self.sceneView anchorForNode:node]);
        ARAnchor *anchor = [self.sceneView anchorForNode:node];
        if([anchor isKindOfClass:[ARPlaneAnchor class]]) {
            NSLog(@"平面锚点: %@",anchor);
            findPlaneAnchor = (ARPlaneAnchor *)anchor;
            break;
        }
    }
    
    if(findPlaneAnchor) {
        SCNNode *node = [self.sceneView nodeForAnchor:findPlaneAnchor];
        //        NSLog(@"%f %f %f",planeAnchor.extent.x,planeAnchor.extent.y,planeAnchor.extent.z);
        SCNBox *plane = [SCNBox boxWithWidth:findPlaneAnchor.extent.x height:0 length:findPlaneAnchor.extent.z chamferRadius:0];
        plane.firstMaterial.diffuse.contents = [UIColor xwai_randomColor];
        SCNNode *planeNode = [SCNNode nodeWithGeometry:plane];
        planeNode.position = SCNVector3Make(findPlaneAnchor.center.x, 0, findPlaneAnchor.center.z);
        [node addChildNode:planeNode];
    }
}
  1. 在相机前方位置新增几何体
- (void)addBoxDemo {
    CGFloat s = 0.1; // 10厘米
    SCNBox *planeBox = [SCNBox boxWithWidth:s height:s length:0.025 chamferRadius:0]; // 以米为单位 0.0025
    // 3. 使用Material渲染3D模型(默认模型是白色的)
    planeBox.firstMaterial.diffuse.contents = [UIColor whiteColor];
    // 4. 创建一个基于3D物体模型的节点
    SCNNode *planeNode = [SCNNode nodeWithGeometry:planeBox];
    // 5. 设置节点的位置为捕捉到的平地的锚点的中心位置
    // SceneKit中节点的位置position是一个基于3D坐标系的矢量坐标SCNVector3Make
    planeNode.position = SCNVector3Make(0.0, 0.0, -0.5); // 以米为单位
    [self.sceneView.scene.rootNode addChildNode:planeNode];
    [planeNode runAction:[SCNAction repeatActionForever:[SCNAction rotateByX:0 y:0 z:2 duration:1]]];
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容