1
\$\begingroup\$

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?

\$\endgroup\$
1
\$\begingroup\$

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)"
    }
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.