问题描述
我正在使用 ARKit 开发一个简单的应用程序,用户可以在其中点击他们的屏幕并在给定位置放置一个节点 (SCNNode)。我希望用户能够将节点放置在原地,无论相机在哪里,这样当他们平移回放置节点的位置时,它仍然在那里。
我已经使用了点击功能,但我注意到当我沿着 x 轴物理移动我的设备时,放置的节点也随之移动。我试图将节点锚定到根节点以外的其他节点,但它没有按预期工作。我试图查找有关如何放置根节点以及是否根据相机计算根节点的文档,这将解释为什么节点与相机一起移动,但也没有运气。
这是放置节点的代码。节点位置使用 scenePoint 放置,它是从触摸位置到使用 SceneKit: unprojectPoint returns same/similar point no matter where you touch screen 完成的场景的投影。
let nodeImg = SCNNode(geometry: SCNSphere(radius: 0.05))
nodeImg.physicsBody? = .static()
nodeImg.geometry?.materials.first?.diffuse.contents = hexColor
nodeImg.geometry?.materials.first?.specular.contents = UIColor.white
nodeImg.position = SCNVector3(scenePoint.x,scenePoint.y,scenePoint.z)
print(nodeImg.position)
sceneView.scene.rootNode.addChildNode(nodeImg)
我认为这与我将 nodeImg 节点作为子节点添加到 rootNode 的事实有关,但我不确定还可以将其锚定到什么。
解决方法
点击时,您需要设置节点的“worldPosition”而不仅仅是“position”
检查此链接:ARKit: position vs worldposition vs simdposition
假设你已经设置了sceneView.allowsCameraControl = false
@objc func handleTapGesture(withGestureRecognizer recognizer: UITapGestureRecognizer) {
let location: CGPoint = recognizer.location(in: self.sceneView)
let hits = self.sceneView.hitTest(location,options: nil)
if let tappednode = hits.first?.node {
nodeImg.worldPosition = tappednode.worldPosition
self.sceneView.scene.rootNode.addChildNode(nodeImg)
}
}