如果您查看Apple Docs,它会声明:
跟踪真实或虚拟对象的位置和方向
相对于相机,创建锚对象并使用 add(anchor:)
方法将它们添加到您的 AR 会话中。
因此,我认为由于您没有使用PlaneDetection,因此如果需要,您需要手动创建ARAnchor:
每当你放置一个虚拟对象时,总是添加一个代表它的位置和方向的 ARAnchor 到 ARSession。移动虚拟对象后,移除旧位置的锚点,并在新位置创建新的锚点。添加锚点会告诉 ARKit 位置很重要,从而提高该区域的世界跟踪质量并帮助虚拟对象相对于真实世界表面保持在原位。
您可以在以下线程What's the difference between using ARAnchor to insert a node and directly insert a node?中阅读更多相关信息
无论如何,为了让您开始,我首先创建了一个名为 currentNode 的SCNNode:
var currentNode: SCNNode?
然后使用UITapGestureRecognizer,我在 touchLocation 手动创建了一个ARAnchor:
@objc func handleTap(_ gesture: UITapGestureRecognizer){
//1. Get The Current Touch Location
let currentTouchLocation = gesture.location(in: self.augmentedRealityView)
//2. If We Have Hit A Feature Point Get The Result
if let hitTest = augmentedRealityView.hitTest(currentTouchLocation, types: [.featurePoint]).last {
//2. Create An Anchore At The World Transform
let anchor = ARAnchor(transform: hitTest.worldTransform)
//3. Add It To The Scene
augmentedRealitySession.add(anchor: anchor)
}
}
添加锚后,我使用ARSCNViewDelegate 回调创建 currentNode,如下所示:
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
if currentNode == nil{
currentNode = SCNNode()
let nodeGeometry = SCNBox(width: 0.2, height: 0.2, length: 0.2, chamferRadius: 0)
nodeGeometry.firstMaterial?.diffuse.contents = UIColor.cyan
currentNode?.geometry = nodeGeometry
currentNode?.position = SCNVector3(anchor.transform.columns.3.x, anchor.transform.columns.3.y, anchor.transform.columns.3.z)
node.addChildNode(currentNode!)
}
}
为了测试它是否有效,例如能够记录相应的ARAnchor,我更改了 tapGesture 方法以将其包含在最后:
if let anchorHitTest = augmentedRealityView.hitTest(currentTouchLocation, options: nil).first,{
print(augmentedRealityView.anchor(for: anchorHitTest.node))
}
在我的ConsoleLog 打印:
Optional(<ARAnchor: 0x1c0535680 identifier="23CFF447-68E9-451D-A64D-17C972EB5F4B" transform=<translation=(-0.006610 -0.095542 -0.357221) rotation=(-0.00° 0.00° 0.00°)>>)
希望对你有帮助...