iosswift3scenekit

SCNNode parent-child relationship in SceneKit?


From my former question, I believe cloning the SCNNode is the way to solve the problem of loading multiple objects. However, I realized there is something wrong.

I did something like

arrow = scnScene.rootNode.childNode(withName: "arrow", recursively:true)
arrow.rotation = SCNVector4(0, 0, 1, M_PI_2)
arrow.position = SCNVector3(x: 0, y: 0, z: -3);
let sign = SCNNode()
for i in 0..<10{
    let node = arrow.clone()
    node.position = SCNVector3(i+1,0,0)
    sign.addChildNode(node)
}
arrow.addChildNode(sign)

I expect there is a row of arrows displaying but actually there is a column of arrows (Translating in x axis but in fact affecting y axis, seems cloned node's coordinate system has been changed) displaying and all of child objects rotate 180 degree. Why?

Before Karl Sigiscar told me to use SCNReferenceNode, I am not sure how should I use it and will it achieve my goal?

Update:

I tried SCNReferenceNode like this:

    let scnScene = SCNScene()

    if let filePath = Bundle.main.path(forResource: "arrowsign", ofType: "dae", inDirectory: "art.scnassets") {
        // ReferenceNode path -> ReferenceNode URL
        let referenceURL = NSURL(fileURLWithPath: filePath)


        if #available(iOS 9.0, *) {
            arrow = SCNReferenceNode(url: referenceURL as URL!)!
            arrow.load()
            arrow.rotation = SCNVector4(0, 0, 1, -M_PI_2)
            arrow.position = SCNVector3(0,0,-5)

            // Create reference node
            for i in 0..<10{
                let referenceNode : SCNReferenceNode = SCNReferenceNode(url: referenceURL as URL)!
                referenceNode.load()
                referenceNode.position = SCNVector3(i+1, 0, 0);
                arrow.addChildNode(referenceNode)
            }
        }
    }
    scnScene.rootNode.addChildNode(arrow)

I didn't rotate child nodes but they rotated automatically (-M_PI_2 degree) when I run it. And I did translate in x axis but in fact there is a column of arrows displaying, rather than a row of arrows. Is that a feature of child-parent node?


Solution

  • After using SCNReferenceNode, I figured out if you add a node to another node as the child, the child node will be set to the parent node's location. For instance, there is a parent node in location (3,4,5), then all of child nodes of it will be located in (3,4,5) at first (you can modify later). So if you want a row of arrows, just modify child nodes' x and keep y & z value be equal to zero. If the parent node applies rotation, the rotation will be applied to child nodes as well.