NEO
NEO

Reputation: 171

How to combine to two or more SCNGeometry / SCNNode into one

As if I would like to create some custom shape by combining some SCNBox and SCNPyramid etc, I can put them together by setting the right positions and geometries. How ever I just can not find a way to combine them as a single unit which can be modified or reacted in physical world. The code below that I would like create a simple house shape SCNNode, and I would like the node attached each other when affected by any collisions and gravity. Can anyone give some hints?

let boxGeo = SCNBox(width: 5, height: 5, length: 5, chamferRadius: 0)
    boxGeo.firstMaterial?.diffuse.contents = UIColor.blueColor()

    let box = SCNNode(geometry: boxGeo)
    box.position = SCNVector3Make(0, -2.5, 0)
    scene.rootNode.addChildNode(box)

    let pyramidGeo  = SCNPyramid(width: 7, height: 7, length: 7)
    pyramidGeo.firstMaterial?.diffuse.contents = UIColor.greenColor()

    let pyramid = SCNNode(geometry: pyramidGeo)
    pyramid.position = SCNVector3Make(0, 0, 0)
    scene.rootNode.addChildNode(pyramid)

enter image description here

Upvotes: 4

Views: 4362

Answers (2)

NEO
NEO

Reputation: 171

Thanks bpedit!

With the childNodes method and the following code to set it a physicsShape, I found the solution for it.

        houseNode.physicsBody = SCNPhysicsBody(type: .Dynamic,
                                      shape: SCNPhysicsShape(node: houseNode,
                                        options: [SCNPhysicsShapeKeepAsCompoundKey: true]))

Upvotes: 1

bpedit
bpedit

Reputation: 1196

Make a container node, simply an empty node without any geometry. Let's call it "houseNode" since that's what it looks like you're building.

let houseNode = SCNNode()

Now make your other two nodes children of this.

houseNode.addChildNode(pyramid)
houseNode.addChildNode(box)

Now use the container node anytime you want to act on the two combined nodes.

Edit: You can effect changes to the geometry of the objects in your container by enumeration:

houseNode.enumerateChildNodesUsingBlock({
       node, stop in
       // change the color of all the children
       node.geometry?.firstMaterial?.diffuse.contents = UIColor.purpleColor()
       // I'm not sure on this next one, I've yet to use "physics".
       houseNode.physicsBody?.affectedByGravity = true
    })

Upvotes: 4

Related Questions