I am trying to add a 3D object to an AR scene with the press of a button. The intent is that the object would spawn at the location of the scene camera when the button is pressed. When the button is pressed, the object appears and rotates as expected, but not in the expected location.
My issue is that the object appears only at the 0,0,0 position. Additional presses of the button places additional objects, but on top of one another in the same coordinates. When I checked to see if the SCNNode was added to the root, it returned nil, so not sure why it's not being added. I've tried a number of different solutions, and I just can't seem to get it to work correctly.
Here is the current code:
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)
}
}
}
I've tried with detecting/adding a horizontal plane and without, but the result was the same. Hardcoding an SCNVector3 doesn't change it, so pretty sure it's something to do with it not getting added to the rootNode.
Just for reference: Xcode 15.2, Building onto a iPhone SE (gen2) device and occasionally some simulators
Turn out that the issue I was having wasn't the code. It was an issue with the scene asset itself. I added a parent node to the scene asset and it worked just fine.