Detecting collisions in sprite kit

The categoryBitMask sets the category that the sprite belongs to, whereas the collisionBitMask sets the category with which the sprite can collide with and not pass-through them.

For collision detection, you need to set the contactTestBitMask. Here, you set the categories of sprites with which you want the contact delegates to be called upon contact.

What you have already done is correct. Here are a few additions you need to do:

_player.physicsBody.contactTestBitMask = blockCategory;
_blok.physicsBody.contactTestBitMask = playerCategory;

Afterwards, implement the contact delegate as follows:

-(void)didBeginContact:(SKPhysicsContact *)contact`
{
NSLog(@"contact detected");

SKPhysicsBody *firstBody;
SKPhysicsBody *secondBody;

if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
{
    firstBody = contact.bodyA;
    secondBody = contact.bodyB;
}
else
{
    firstBody = contact.bodyB;
    secondBody = contact.bodyA;
}

//Your first body is the block, secondbody is the player.
//Implement relevant code here.

}

For a good explanation on implementing collision detection, look at this tutorial.

Leave a Comment