claassenApps claassenApps - 5 months ago 7
iOS Question

Most Efficient Way to Check Collisions in didBeginContact

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?

Answer

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