Collision in Sprite Kit

This example is 3 characters, player, point(coin), enemy.
3 characters have each feature in Game.


World in Scene

We can apply physics world in Scene.


Apply physics in object


Wrap physics world to object


self.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:self.frame.size];
//self.physicsBody.allowsRotation = NO;
//self.physicsBody.affectedByGravity = NO;   // This is gravity setting      

You need to set physicsBody in your object.

Collision Setting and Bit mask

Bit mask is important.
This bit mask is thing to decide collision behaviour
Each objects should have bit mask.

Bit mask Example

static const int playerCollisionBitMask = 0x01 << 0;
static const int pointCollisionBitMask = 0x02 << 0;
static const int enemyCollisionBitMask = 0x03 << 0;

<b>SKNode</b> key parameters are <b>collisionBitMask, categoryBitMask, contactTestBitMask</b> 
Evaluation of collision is based on these parameters.

Object A

Object B

To avoid collision in physics meaning, <b>collisionBitMask = 0</b>. 
Collision has happened when ObjectA categoryBitMask and 

<h4>Set Collision</h4>
objA.categoryBitMask = playerCollisionBitMask;
objA.contactTestBitMask = pointCollisionBitMask | enemyCollisionBitMask;
objB.categoryBitMask = pointCollisionBitMask;
objB.contactTestBitMask = playerCollisionBitMask;
objC.categoryBitMask = enemyCollisionBitMask;
objC.contactTestBitMask = playerCollisionBitMask;

Contact SKPhysicsContactDelegate

To manage special collision behaviour, we need to implement SKPhysicsContactDelegate.
When collision has happened.

Prepare(set delegate)


@interface GameScene : SKScene<SKPhysicsContactDelegate>


@implementation GameScene
- (id)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {
        // Setup here
        self.physicsWorld.contactDelegate = self;
    return self;

#pragma mark - SKPhysicsContactDelegate
- (void)didBeginContact:(SKPhysicsContact *)contact {

    // contact.bodyA.node : Node A  This is SKNode class
    // contact.bodyB.node : Node B  This is also SKNode class
    // This method is called when collision has happened