我正在尝试通过按下按钮将 3D 对象添加到 AR 场景中。目的是当按下按钮时该对象将在场景摄像机的位置生成。按下按钮时,对象会按预期出现并旋转,但不在预期位置。
我的问题是该对象仅出现在 0,0,0 位置。再次按下该按钮会放置其他对象,但在相同的坐标中将它们相互叠加。当我检查 SCNNode 是否已添加到根时,它返回 nil,所以不确定为什么没有添加它。我尝试了多种不同的解决方案,但似乎无法让它正常工作。
这是当前代码:
override func viewDidLoad() {
super.viewDidLoad()
// Set the View Controller as the AR Scene delegate
sceneView.delegate = self
sceneView.autoenablesDefaultLighting = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Create a session configuration
let configuration = ARWorldTrackingConfiguration()
//configuration.planeDetection = [.horizontal]
// Run the view's session
sceneView.session.run(configuration)
}
@IBAction func DropTokenPressed(_ sender: Any) {
if let cameraPosition = sceneView.pointOfView?.position {
//debug text - show coordinates on screen
tempText.text = "x: \(cameraPosition.x)\ny: \(cameraPosition.y)\n
z: \(cameraPosition.z)"
let scene = SCNScene(named: "art.scnassets/Been_Token_v2.scn")!
if let sceneNode = scene.rootNode.childNode(withName: "token", recursively: true){
sceneNode.position = cameraPosition
print(sceneNode)
sceneView.scene.rootNode.addChildNode(sceneNode)
}
}
}
我尝试过检测/添加水平面和不检测/添加水平面,但结果是相同的。对 SCNVector3 进行硬编码不会改变它,所以很确定这与它没有被添加到 rootNode 有关。
仅供参考:Xcode 15.2,构建到 iPhone SE(gen2)设备上,偶尔还有一些模拟器
事实证明我遇到的问题不是代码。这是场景资产本身的问题。我向场景资源添加了一个父节点,它工作得很好。