3

I have created a sprite with circle shape physics body. I want to change the circle shape into a rectangle shaped physics body on contact/collision with another body. I believe this should be done in the didBeginContact. Here's what I've done so far

ball.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2)
self.addChild(ball)
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.size.width/2)
ball.physicsBody?.friction = 0
ball.physicsBody?.restitution = 1.2
ball.physicsBody?.linearDamping = 0
ball.physicsBody?.angularDamping = 0
ball.physicsBody?.allowsRotation = false
ball.physicsBody?.applyImpulse(CGVectorMake(2, -4))

func didBeginContact(contact: SKPhysicsContact) {
    var firstBody : SKPhysicsBody
    var secondBody : SKPhysicsBody

    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask  {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    }
    else    {
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }

    if firstBody.categoryBitMask == ballCategory && secondBody.categoryBitMask == enemyCategory  {

        //change ball physics shape here
    }
}
chronos
  • 517
  • 1
  • 5
  • 14

1 Answers1

0

Remember that a physics body is something that belongs to a node. It's simply a property, and its dependent on that node to exist. All you have to do is swap one body for another in your node's physicsBody property:

//inside of didBeginContact, say you want to change firstBody's body to rectangle
firstBody.node.physicsBody = SKPhysicsBody(rectangleOfSize:...)
MaxKargin
  • 1,560
  • 11
  • 13
  • this worked, but after I changed the body contacts weren't recognized again. – chronos Oct 05 '15 at 14:51
  • I asked another question with more details of the issue http://stackoverflow.com/questions/32891830/contacts-not-recognized-when-body-is-changed-from-circle-to-rectangle – chronos Oct 05 '15 at 14:53