Sprite Kit - Detect contact

ios, objective-c, sprite-kit

Solution

Your collision detection need's Delegate Methods.

in your MyScene.h your code should look like this:

@interface MyScene : SKScene <SKPhysicsContactDelegate>

In your MyScene.m add this inside your initWithSize:

self.physicsWorld.contactDelegate = self;

Now you need to implement the delegate method didBeginContact:

- (void)didBeginContact:(SKPhysicsContact *)contact {
    uint32_t collision = (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask);

    if (collision == (playerCategory | enemyCategory)) {
        // Do your stuff
    }
}

Problem

I have two Sprite Nodes: ``` -(void)createPlayer { SKSpriteNode *player = [SKSpriteNode node]; player.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:enemy.size]; player.physicsBody.categoryBitMask = playerCategory; player.physicsBody.contactTestBitMask = enemyCategory; player.position = CGPointMake(100, 160); player.name = @"player"; player.zPosition = 100; [self addChild:player]; } -(void)createEnemy { SKSpriteNode *enemy = [SKSpriteNode node]; enemy.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:enemy.size]; enemy.physicsBody.categoryBitMask = enemyCategory; enemy.physicsBody.contactTestBitMask = playerCategory; enemy.position = CGPointMake(300, 160); enemy.name = @"player"; enemy.zPosition = 100; [self addChild:enemy]; } ``` And the following in MyScene.h ``` static const uint32_t playerCategory = 0x1 << 0; static const uint32_t enemyCategory = 0x1 << 1; ``` How do I detect if they make contact, so I can add an action as a result of their contact?

Original source