ARKit--HITTEST模式

HITTEST介绍

点击测试(hittest),找到与相机图像中的某个点所对应的真实世界面。如果您在 Session (会话) 配置当中启用了 planeDetection 配置的话,那么 ARKit 就会去检测相机图像当中的水平面,并报告其位置和大小。您可以使用点击测试所生成的结果,或者使用所检测到的水平面,从而就可以在场景当中放置虚拟内容,或者与之进行交互。
HITTEST可以想象成,发射一个射线到平面上,碰到的平面的点都做成ARHitTestResult返回。

API

ARSCNView类里定义了hittest的API.

/* 
@param point A point in the view's coordinate system.
                屏幕坐标系里的点
 @param types The types of results to search for.
                 搜索类型
*/
- (NSArray *)hitTest:(CGPoint)point 
types:(ARHitTestResultType)types;

一个手指触碰点HITEST的例子

手指触摸的时候,做一次hittest,返回3d坐标系里触摸的点,放一个小物品。

//定义点击手势
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] 
initWithTarget:self 
action:@selector(handleTapFrom:)];

- (void)handleTapFrom: (UITapGestureRecognizer *)recognizer {
  // Take the screen space tap coordinates and pass them to the hitTest method on the ARSCNView instance
  CGPoint tapPoint = [recognizer locationInView:self.sceneView];
  NSArray *result = [self.sceneView hitTest:tapPoint types:ARHitTestResultTypeExistingPlaneUsingExtent];
  
  // If the intersection ray passes through any plane geometry they will be returned, with the planes
  // ordered by distance from the camera
  if (result.count == 0) {
    return;
  }
  
  // If there are multiple hits, just pick the closest plane
  ARHitTestResult * hitResult = [result firstObject];
  [self insertGeometry:hitResult];
}

hitResult里面worldTransform,直接返回在3D世界的坐标,下面的代码是插入一个小小的cube做一个演示。

- (void)insertGeometry:(ARHitTestResult *)hitResult {
  // Right now we just insert a simple cube, later we will improve these to be more
  // interesting and have better texture and shading
  
  float dimension = 0.1;
  SCNBox *cube = [SCNBox boxWithWidth:dimension height:dimension length:dimension chamferRadius:0];
  SCNNode *node = [SCNNode nodeWithGeometry:cube];
  
  // The physicsBody tells SceneKit this geometry should be manipulated by the physics engine
  node.physicsBody = [SCNPhysicsBody bodyWithType:SCNPhysicsBodyTypeDynamic shape:nil];
  node.physicsBody.mass = 2.0;
  node.physicsBody.categoryBitMask = CollisionCategoryCube;
  
  // We insert the geometry slightly above the point the user tapped, so that it drops onto the plane
  // using the physics engine
  float insertionYOffset = 0.5;
  node.position = SCNVector3Make(
                                 hitResult.worldTransform.columns[3].x,
                                 hitResult.worldTransform.columns[3].y + insertionYOffset,
                                 hitResult.worldTransform.columns[3].z
                                 );
  [self.sceneView.scene.rootNode addChildNode:node];
  [self.boxes addObject:node];
}

具体代码参看例子
demo

你可能感兴趣的:(ARKit--HITTEST模式)