Question

I'm trying to figure out how to detect when the contact between two bodies ends. I'm working on a car game something like alpine crawler and only when the rear wheel is touching the ground the car is able to accelerate.

This is my code for now but it doesn't work proper:

- (void) didBeginContact:(SKPhysicsContact *)contact
{
    if (([contact.bodyB.node.name isEqualToString:@"rearWheel"] &&
         [contact.bodyA.node.name isEqualToString:@"ground"])) {
        isWheelOnGround = YES;
    }
}

-(void) didEndContact:(SKPhysicsContact *)contact {

        if (([contact.bodyB.node.name isEqualToString:@"rearWheel"] &&
             [contact.bodyA.node.name isEqualToString:@"ground"])) {
            isWheelOnGround = NO;
        }
    }
Was it helpful?

Solution

You need to implement the contact delegate correctly and set bitmasks on bodies for the contact notifications to fire up. To do that, put this beneath your imports:

typedef NS_OPTIONS(uint32_t, CNPhysicsCategory) {
    CNPhysicsCategoryWheel   = 1 << 0, // 0001 = 1
    CNPhysicsCategoryGround  = 1 << 1, // 0010 = 2
};

@interface YourSceneNameHere() <SKPhysicsContactDelegate>
@end


Then, as you initialize, add the scene as the contact delegate:

self.physicsWorld.contactDelegate = self;


Now, to apply those masks to your bodies - the category they are in, and what category of bodies they will be sending contact notifications for:

wheel.physicsBody.categoryBitMask = CNPhysicsCategoryWheel;
wheel.physicsBody.contactTestBitMask = CNPhysicsCategoryGround;

ground.physicsBody.categoryBitMask = CNPhysicsCategoryGround;
ground.physicsBody.contactTestBitMask = CNPhysicsCategoryWheel;


In the contact method, you have no control over which body is bodyA, and which bodyB:

- (void) didBeginContact:(SKPhysicsContact *)contact {
    uint32_t contactTest = (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask);
    if (contactTest == (CNPhysicsCategoryWheel | CNPhysicsCategoryGround)) {
        isWheelOnGround = YES;
    }   
}

Similarly for didEndContact. Good luck!

For another example of this and a thorough explanation, refer to the 'Working with collisions and contacts' section of the SK Programming Guide.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top