didBeginContact - bodyA & bodyB end Contact if one

2019-08-29 10:10发布

问题:

Here is the deal, I've got a basket, an Apple and an Orange bodies. We are going to drop them into the basket.

I also want to know the presence of the Apple inside the basket, so I go ahead and add a didEndContact method.

Lets assume the apple is already inside the basket. Now I drop the Orange in the basket, everything works fine until the Orange hits both the Apple and the surface which is the basket.

As soon as the Orange hits the Apple while it's seating in the basket, Apple category ends contact with basket category and therefore we get ballOneIntTheBasket = NO. bodyA becomes orange category and bodyB becomes basket category

How do I get apple category to stay connected with all the connected bodies?

didBeginContact code

if (bodyA == appleCategory && bodyB == basketCategory) {
appleInTheBasket= YES;
}

if (bodyA == orangeCategory && bodyB == basketCategory) {
orangeInTheBasket = true;
}

didEndContact code

if (bodyA == appleCategory && bodyB == basketCategory) {
appleInTheBasket = NO;
}

回答1:

Instead of using the contact delegate for this, you can use the allContactedBodies property of SKPhysicsBody.

So, using

basket.physicsBody.allContactedBodies

will return you a NSArray of all SKPhysicsBody objects currently in contact with the basket.

You can use this property in the -update: method to monitor the basket.