如何在接触/碰撞时改变物理体形状

时间:2015-09-24 22:46:33

标签: swift sprite-kit

我创建了一个带有圆形物理体的精灵。我想在与另一个身体接触/碰撞时将圆形变成一个矩形的物理体。我相信这应该在didBeginContact中完成。这是我到目前为止所做的事情

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
    }
}

1 个答案:

答案 0 :(得分:0)

请记住,物理主体属于某个节点。它只是一个属性,它依赖于该节点存在。您所要做的就是在节点的physicsBody属性中将一个主体换成另一个主体:

//inside of didBeginContact, say you want to change firstBody's body to rectangle
firstBody.node.physicsBody = SKPhysicsBody(rectangleOfSize:...)