HITTEST介紹
點(diǎn)擊測(cè)試(hittest),找到與相機(jī)圖像中的某個(gè)點(diǎn)所對(duì)應(yīng)的真實(shí)世界面是掰。如果您在 Session (會(huì)話) 配置當(dāng)中啟用了 planeDetection 配置的話,那么 ARKit 就會(huì)去檢測(cè)相機(jī)圖像當(dāng)中的水平面,并報(bào)告其位置和大小睹栖。您可以使用點(diǎn)擊測(cè)試所生成的結(jié)果飒责,或者使用所檢測(cè)到的水平面梦抢,從而就可以在場(chǎng)景當(dāng)中放置虛擬內(nèi)容案糙,或者與之進(jìn)行交互地啰。
HITTEST可以想象成策彤,發(fā)射一個(gè)射線到平面上栓袖,碰到的平面的點(diǎn)都做成ARHitTestResult返回匣摘。
API
ARSCNView類里定義了hittest的API.
/*
@param point A point in the view's coordinate system.
屏幕坐標(biāo)系里的點(diǎn)
@param types The types of results to search for.
搜索類型
*/
- (NSArray<ARHitTestResult *> *)hitTest:(CGPoint)point
types:(ARHitTestResultType)types;
一個(gè)手指觸碰點(diǎn)HITEST的例子
手指觸摸的時(shí)候,做一次hittest裹刮,返回3d坐標(biāo)系里觸摸的點(diǎn)音榜,放一個(gè)小物品。
//定義點(diǎn)擊手勢(shì)
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<ARHitTestResult *> *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世界的坐標(biāo)赠叼,下面的代碼是插入一個(gè)小小的cube做一個(gè)演示。
- (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