您应该点击位置并使用世界坐标正确放置立方体。我不确定(0,0,0)是否是 ARKit 的正常位置。您可以尝试如下操作:
将其放在您的 viewDidLoad 中:
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapFrom))
tapGestureRecognizer.numberOfTapsRequired = 1
self.sceneView.addGestureRecognizer(tapGestureRecognizer)
然后添加此方法:
@objc func handleTapFrom(recognizer: UITapGestureRecognizer) {
let tapPoint = recognizer.location(in: self.sceneView)
let result = self.sceneView.hitTest(tapPoint, types: ARHitTestResult.ResultType.existingPlaneUsingExtent)
if result.count == 0 {
return
}
let hitResult = result.first
let box = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0)
let node = SCNNode(geometry: box)
node.physicsBody = SCNPhysicsBody(type: SCNPhysicsBodyType.static, shape: nil)
node.position = SCNVector3Make(hitResult.worldTransform.columns.3.x, hitResult.worldTransform.columns.3.y, hitResult.worldTransform.columns.3.z)
sceneView.scene.rootNode.addChildNode(node)
}
然后,当您点击检测到的平面时,它将在您点击的平面上添加一个框。