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



我创建了一个具有圆形物理体的精灵。我想把圆的形状变成一个矩形的物理体与另一个物体接触/碰撞。我认为这应该在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
    }
}

记住物理体是属于节点的东西。它只是一个属性,它依赖于那个节点的存在。你所要做的就是在节点的physicsBody属性中将一个body替换为另一个body:

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

最新更新