1
votes

I am trying to merge several sprite nodes into a single unified physics body. For example:

enter image description here

I am trying to unify these three barriers into a single sprite node. I have looked at other questions and I have tried the following:

  • Making one of the nodes the parent, adding the other nodes to the parent and setting them non-dynamic. However, this disables the movement of the children nodes.

  • I tried creating a node with the a physics body of all the other barriers:

    SKPhysicsBody(bodies: self.allNodePhysicsBodies)
    
  • I also tried creating a joint of the nodes with the "parent" node:

    let joint = SKPhysicsJointFixed.joint(withBodyA: merge[0].physicsBody!, bodyB: merge[1].physicsBody!, anchor: CGPoint(x: 0, y: 0))
    let joint1 = SKPhysicsJointFixed.joint(withBodyA: merge[0].physicsBody!, bodyB: merge[2].physicsBody!, anchor: CGPoint(x: 0, y: 0))
    
    
    self.physicsWorld.add(joint1)
    self.physicsWorld.add(joint)
    

    However, this does not unite the physics bodies. It does not create a single physics body.

How can I accomplish this? I was thinking my only option was to unite the textures before I even create the node.

EDIT

Attempt to unite the barriers with a physics body again:

    let ourUnionOfBodies = SKPhysicsBody(bodies: [merge[0].physicsBody!, merge[1].physicsBody!, merge[2].physicsBody!])
    ourUnionOfBodies.isDynamic = true

    merge[2].physicsBody = ourUnionOfBodies
2

2 Answers

1
votes

init(bodies: [SKPhysicsBody])

This is what you need.

However you're seemingly doing something wrong in using it. I assume what you're forgetting is to then set the properties of the newly created physics body to what you need for interaction with your world and other objects within it.

I'd make the same mistake, because I'd assume that all the properties of the unioned bodies would be adopted by the new body, particularly if they're all the same. But this is not the case.

From the docs:

The properties on the children, such as mass or friction, are ignored. Only the shapes of the child bodies are used.

So having created your new body from the union of the bodies in the array, now you need to manually set all the properties of this body as you desire/need.

eg.

// Putting the right bodies together, correctly

let ourUnionOfBodies = SKPhysicsBody(bodies: [bodyMine, bodyBeyonce])
ourUnionOfBodies.isDynamic = YES!

// and the result = TWINS!
0
votes

You could draw the barriers inside a CGMutablePath and then use this as the physicsbody of one node, although it's a little long work to do.

let bodyPath = CGMutablePath()
bodyPath.move(to: CGPoint(x: ..., y: ...)) // Use move(to:) to “move the pen” somewhere without “drawing”
bodyPath.addLine(to: CGPoint(x: ..., y: ...)) // Use addLine(to:) to trace a line starting from the “pen”’s last position to the specified CGPoint position
// ...
physicsBody = SKPhysicsBody(polygonFrom: bodyPath)