问题
What's the best way to check for collision using SpriteKit's didBeginContact
method. I'm currently checking by class and doing something like this:
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()
}
}
I'm doing this a bunch of times in the didBeginContact
method because I have lots of different objects that can interact with each other. Is it more efficient to be checking by the bit masks? Also, is there a way to cut down on needing to basically duplicate all the code by checking nodeA and nodeB as the same class?
回答1:
Use category 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")
}
}
来源:https://stackoverflow.com/questions/37996254/most-efficient-way-to-check-collisions-in-didbegincontact