Alfro
Alfro

Reputation: 1544

Two or more collisions at same time in Sprite Kit

I have a little problem and can't know by myself the solution. I'm handling collisions with Sprite Kit and I have a problem when my hero collides with two objects at same time (example with the ground and a cube in the air).

I got booleans that tell when the hero is jumping and when he is running at a great speed and when he is running slow (example when he collides with a wall made of cubes).

In this last example my booleans got crazy and sometimes my hero just pass over the cubes cause the speed don't slow down. Sometimes the boolean "is jumping" activates too, so in resume it goes crazy and I think it's because the handling collisions method (didBeginContact) only allows two contact bodies, contact.bodyA and contact.bodyB.

I would like to know if I can edit a file to add a contact.bodyC and what file do I need to edit? and if yes I will handle with this, I think with three contact bodies I will be able to program all the posible cases. If not then I suppose I will have to remove those cube walls or change their category bit mask...

Upvotes: 0

Views: 418

Answers (1)

zago
zago

Reputation: 532

Maybe queuing the contacts and handle then in -update is what you need. For example:

Declare an instance variable called NSMutableArray *_contactQueue; Add the contacts to the array:

-(void) didBeginContact:(SKPhysicsContact *)contact
{
    [_contactQueue addObject:contact];
}

Create a method to handle each contact in sync with your game ticks:

-(void)processContactsForUpdate:(NSTimeInterval)currentTime
{
    for (SKPhysicsContact * contact in [_contactQueue copy]) {
        [self handleContact:contact];
        [_contactQueue removeObject:contact];
    }
}

Call this method from update:

[self processContactsForUpdate:currentTime];

Then implement your handle method that will handle the contact.

-(void) handleContact:(SKPhysicsContact *)contact
{
    // What you are doing in your current didBeginContact method
}

You can only handle the contact of two bodies, but in this way it's synchronized with every frame. I learned about this following a SpriteKit tutorial at this tutorial

Upvotes: 3

Related Questions