swiftskphysicsbody

Having problems with a Parent and Child nodes when they each have an SKPhysicsBody


I have an SKSpriteNode that I set above the screen, so that it'll drop from above. So it does have an SKPhysicsBody that affectedByGravity. But that's only so it drops down from above, there will be no collision detection. The node itself has 6 children evenly spread out.

However I need each children to have be able to detect collisions. So I give them an SKPhysicsBody. When I do this they seem to detach from the parent node and cause a mess. Setting affectedByGravity to false does nothing. Is there a step I'm missing, something that will hammer them in place to their parent?

The reason for the parent SKNode is because there will be multiple, and it's easier to move all the children per SKNode, as well as destroy them in one shot.

On the left is what I want, on the right is the mess that occurs when I give each child its own SKPhysicsBody.

I should add that if I set the children’s isDynamic to false, then they hold the parent up above the screen so it never falls.

Before and After


Solution

  • My first problem was that I had the Category masks set incorrectly.

    I made sure that both parent and children were in the same category,

    Then I used SKContraint to essentially nail each child to its spot in the parent. at this moment it appears to work without any glitches.

    The code below is run for each child at its creation.

    let rangeX       = SKRange(lowerLimit: indexSpacing, upperLimit: indexSpacing)
    let contraintX   = SKConstraint.positionX(rangeX)
    let rangeY       = SKRange(lowerLimit: (self.size.height/2), upperLimit (self.size.height/2))
    let contraintY   = SKConstraint.positionY(rangeY)
    self.constraints = [contraintX, contraintY]