2
votes

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?

1
And what's the problem? Where do you have difficulty? - El Tomato
Just as I said in the post above. How do I detect if they make contact, so I can add an action as a result of their contact? So, if player makes contact with enemy, do whatever.. - user2255273
assign a contact delegate to your SKPhysicsWorld developer.apple.com/library/ios/documentation/SpriteKit/… then listen to contact delegate messages: developer.apple.com/library/ios/documentation/SpriteKit/… - LearnCocos2D

1 Answers

8
votes

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
    }
}