Search code examples
swiftnodesscenekitaugmented-realityarkit

Swift Error – Attempting to add a Parent node as a Child node


I am working on trying to take a .dae file I have and display it once it recognises the first image file I have in photos. Unfortunately, I am receiving an error that a parent node is being added as a child node and not understanding where this is happening.

Any ideas?

import UIKit
import SceneKit
import ARKit

class PlaneTrackingViewController: UIViewController, ARSCNViewDelegate {

    @IBOutlet weak var ARPlaneView: ARSCNView!

    override func viewDidLoad() {
        super.viewDidLoad()

        ARPlaneView.delegate = self

        let scene = SCNScene(named: "Art.scnassets/LoadScene.scn")!

        ARPlaneView.scene = scene
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        let configuration = ARImageTrackingConfiguration()

        guard let trackedImages = ARReferenceImage.referenceImages(inGroupNamed: "Photos", bundle: Bundle.main) else {print ("No Images Available")
            return
        }

        configuration.trackingImages = trackedImages
        configuration.maximumNumberOfTrackedImages = 1
        ARPlaneView.session.run(configuration)
    }

    override func viewWillDisappear(_ animated: Bool) {
        ARPlaneView.session.pause()
    }

    func renderer(_ renderer:SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
        let node = SCNNode()

        if let imageAnchor = anchor as? ARImageAnchor {
            let plane = SCNPlane(width: imageAnchor.referenceImage.physicalSize.width, height: imageAnchor.referenceImage.physicalSize.height)

            plane.firstMaterial?.diffuse.contents = UIColor(white: 1, alpha: 0.6)

            let planeNode = SCNNode(geometry: plane)
            planeNode.eulerAngles.x = -.pi / 2

            let motorScene = SCNScene(named: "Art.scnassets/ACMotor/ACMotor.dae")!
            let motorNode = motorScene.rootNode.childNodes.first!

            motorNode.position = SCNVector3Zero
            motorNode.position.z = 0.3

            motorNode.addChildNode(motorNode)
            node.addChildNode(planeNode)
        }           
        return node
    }
}

Solution

  • It should be written this way: scene.rootNode.addChildNode(node)

    or in your case:

    motorScene.rootNode.addChildNode(motorNode)