Search code examples
swiftarkitscnnode

Need to SCNNode within restricted area


I have created a SCNNode object on a SCNPlane object. Both objects are added to the scene view root node, like below:

scView.scene.rootNode.addChildNode(ballNode)
scView.scene.rootNode.addChildNode(planeNode)

Now, my issue is that the ball node is moving out of the plane node boundary.

When I tried to add ballNode as planeNode's child then, the ball node is not getting added to a plane as expected. It behaves very strangely.

Basically, I need to restrict the movement of ballNode within planeNode area. How can I do it?


Solution

  • Great question!

    When adding a child node to another node, there are no constraints being implicitly applied to the child, aside from existing within the infinite coordinate space of the parent node.

    While changing the transform (eg position) of the parent node will directly apply to all child nodes, each child node can still freely transform within the parent nodes local coordinate space.

    It'd be a good idea to read the SCNNode docs if you haven't already, as it covers the foundational aspects.

    To do what you want, when moving the ball in your gameloop, you will need to manually check whether or not that ball is outside the boundary you are trying to enforce, and change its position accordingly.

    Depending on your desired outcome, you may want to also check out SCNPhysicsBody as a way to construct your scene with implied physical boundaries.