使用SpriteKit的didBeginContact
方法检查碰撞的最佳方法是什么。我目前正按班级检查并做这样的事情:
if let thisMine = nodeA as? Mine {
if nodeB is Player {
thisMine.explode()
}
}
else if let thisMine = nodeB as? Mine {
if nodeA is Player {
thisMine.explode()
}
}
我在didBeginContact
方法中做了很多次,因为我有很多不同的对象可以互相交互。通过位掩码进行检查是否更有效?另外,有没有办法通过将nodeA和nodeB作为同一个类来减少基本上需要复制所有代码?
答案 0 :(得分:2)
使用类别bitMasks:
func didBeginContact(contact: SKPhysicsContact) {
let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
switch contactMask {
case categoryBitMask.player | categoryBitMask.thisMine:
print("Collision between player and thisMine")
let mineNode = contact.bodyA.categoryBitMask == categoryBitMask.thisMine ? contact.bodyA.node! : contact.bodyB.node!
mineNode.explode()
default :
//Some other contact has occurred
print("Some other contact")
}
}