Search code examples
swiftparent-childarkitios12

Exchange nodes of 3D Model in ARKit


I have a car model. This model contains a lot of groups (doors, tires, windows, body). I would like to change the model of the tires by button press. But I have trouble finding the correct node. My current idea was to search through all the child nodes of the car and when I find the tires, replace them.

My code:

func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
    guard anchor is ARImageAnchor else { return }

    guard let carNode = sceneView.scene.rootNode.childNode(withName: "Car", recursively: false) else { return }
    node.addChildNode(carNode)

@IBAction func tireChangePressed(_ sender: UIButton) {
var exchangeTires = sceneView.scene.rootNode.childNode(withName: "Tires 2")
    self.sceneView.scene.rootNode.enumerateChildNodes { (node, _) in
        if node.name == "Tires"{
// here I try to exchange the node namend "Tires" with the optional node named "Tires 2"
            node = exchangeTires
        }
    }
}

But it keeps throwing the error that node is a let constant. Should I use other method to iterate through all the child nodes or what could be the problem?


Solution

  • SCNNode and the node tree work analogously to UIView and the view tree, so instead of trying to set the existing node equal to something else you should:

    1. Get the parent node of the target with parent
    2. Remove the target node with removeFromParentNode()
    3. Add the new child node to the parent with addChildNode(_:)