替代 didBeginContact
如果你使用簡單類別,每個物理主體只屬於一個類別,那麼 didBeginContact 的這種替代形式可能更具可讀性:
func didBeginContact(contact: SKPhysicsContact) {
let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
switch contactMask {
case categoryBitMask.player | categoryBitMask.enemy:
print("Collision between player and enemy")
let enemyNode = contact.bodyA.categoryBitMask == categoryBitMask.enemy ? contact.bodyA.node! : contact.bodyB.node!
enemyNode.explode()
score += 10
case categoryBitMask.enemy | categoryBitMask.enemy:
print("Collision between enemy and enemy")
contact.bodyA.node.explode()
contact.bodyB.node.explode()
default :
//Some other contact has occurred
print("Some other contact")
}
}