How do you set multiple collision rules with Swift and SpriteKit?

| | August 4, 2015

So basically I’ve got 2 types of balls and 2 types of enemies. Green can delete red only, red can hit delete only. Here’s what I have for the first collision test:

 func didBeginContact(contact: SKPhysicsContact) {

        // 1. Create local variables for two physics bodies
        var firstBody: SKPhysicsBody
        var secondBody: SKPhysicsBody

        // 2. Assign the two physics bodies so that the one with the lower category 
        // is always stored in firstBody
        if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
            firstBody = contact.bodyA
            secondBody = contact.bodyB
        } else {
            firstBody = contact.bodyB
            secondBody = contact.bodyA
        }

        // 3. react to the contact between ball and bottom
        if firstBody.categoryBitMask == RedBallCategory && 
           secondBody.categoryBitMask == GreenBarCategory {

            (secondBody.node!.removeFromParent())
            score++
            scoreLabel.text = "(score)"
        }
    }

This works as expected, red ball hits the green bar and it deletes him.

You can’t just make a func didBeginContact 2 and change the bit masks as far as I’m aware..or at least it didn’t work when I tried it, so how do you handle multiple rules for collision? All of the basic tutorials I’ve seen handle something like one bullet hitting one type of enemy. What if you have 2 “bullets” and 2 enemies?

One Response to “How do you set multiple collision rules with Swift and SpriteKit?”

  1. Didn’t realize it was as simple as just adding to the if statement. I thought I had already tried that.

    func didBeginContact(contact: SKPhysicsContact) {
    
        var firstBody: SKPhysicsBody
        var secondBody: SKPhysicsBody
    
        if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
            firstBody = contact.bodyA
            secondBody = contact.bodyB
        } else {
            firstBody = contact.bodyB
            secondBody = contact.bodyA
        }
    
    
        if firstBody.categoryBitMask == RedBallCategory && 
           secondBody.categoryBitMask == GreenBarCategory {
    
            (secondBody.node!.removeFromParent())
            score++
            scoreLabel.text = "(score)"
        } else if firstBody.categoryBitMask == GreenBallCategory && 
                  secondBody.categoryBitMask == RedBarCategory {
    
            (secondBody.node!.removeFromParent())
            score++
            scoreLabel.text = "(score)"
        }
    

Leave a Reply