首页 > 解决方案 > 相机沿x轴移动时如何限制SCNNode移动?

问题描述

我正在使用 ARKit 开发一个简单的应用程序,用户可以在其中点击他们的屏幕并将节点 (SCNNode) 放置在给定位置。我希望用户能够放置无论相机在哪里都保持原位的节点,这样当他们平移回他们放置节点的位置时,它仍然在那里。

我已经获得了点击功能,但我注意到当我沿着 x 轴物理移动设备时,放置的节点也会随之移动。我试图将节点锚定到根节点以外的地方,但它没有按预期工作。我试图查找有关如何放置根节点的文档,以及它是否是基于相机计算的,这将解释为什么节点会随着相机移动,但那里也没有运气。

这是放置节点的代码。节点位置使用 scenePoint 放置,它是从触摸位置到使用SceneKit 完成的场景的投影: unprojectPoint 无论您在哪里触摸屏幕都会返回相同/相似的点

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 的事实有关,但我不确定将它锚定到什么。

标签: iosswiftarkitscnnode

解决方案


点击时您需要设置节点的“worldPosition”,而不仅仅是“位置”

检查此链接:ARKit:位置 vs 世界位置 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)
   }
}

推荐阅读