claassenApps claassenApps - 3 months ago 6x
iOS Question

Most Efficient Way to Check Collisions in didBeginContact

What's the best way to check for collision using SpriteKit's

method. I'm currently checking by class and doing something like this:

if let thisMine = nodeA as? Mine {
if nodeB is Player {
else if let thisMine = nodeB as? Mine {
if nodeA is Player {

I'm doing this a bunch of times in the
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?


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!

        default :
           //Some other contact has occurred
           print("Some other contact")