Nielsapp
Nielsapp

Reputation: 302

How to receive a notification when two bodies do not make contact?

In DidBeginContact I like to be notified when two bodies do not make contact.

I tried using the !(NOT) operator, but it didn't work.

if (!(firstBody.categoryBitMask == kBrickCategory && secondBody.categoryBitMask == kCarCategory)) {
    NSLog(@"Hit");

Upvotes: 2

Views: 36

Answers (1)

Dion Larson
Dion Larson

Reputation: 868

didBeginContact only gets called when a collision happens. You set a Bool in update to false and set it true in didBeginContact if there was a collision. Check it in didFinishUpdate and take action accordingly.

Sample code is in Swift but should be easy to convert to Objective-C.

class MyScene: SKScene, SKPhysicsContactDelegate {

    var contactMadeThisFrame = false

    override func update(currentTime: NSTimeInterval) {
        contactMadeThisFrame = false
    }

    func didBeginContact(contact: SKPhysicsContact) {
        let firstBody = contact.bodyA
        let secondBody = contact.bodyB
        if firstBody.categoryBitMask == kBrickCategory && secondBody.categoryBitMask == kCarCategory {
            contactMadeThisFrame = true
        }
    }

    override func didFinishUpdate() {
        if !contactMadeThisFrame {
            print("Hit")
        }
    }
}

If you want to check on a per node basis (take actions only on nodes that did not make contact), then you can iterate through the bodies and check if physicsBody.allContactedBodies count is zero. Do this in didFinishUpdate.

Upvotes: 1

Related Questions