Banshi
Banshi

Reputation: 1345

Collision detection between two SKSpriteNode in SpriteKit?

I have to detect collision between two SKSpriteNode(wall, man) which is the child of a SKNode background. The background node is child of main SKScene gameScene class. When I want to detect collision using the method

- (void) didBeginContact:(SKPhysicsContact *)contact {
    SKPhysicsBody *firstBody, *secondBody;

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

But no collision detection is found. Please help.

Upvotes: 1

Views: 606

Answers (1)

godel9
godel9

Reputation: 7390

You're probably having one of two issues:

  1. You didn't set the contactDelegate property of your SKPhysicsWorld object.

  2. You didn't set your category and contact test bits correctly.

Here's how to set the category and contact test bits:

#define kCategoryOne (1 << 0)
#define kCategoryTwo (1 << 1)

bodyA.categoryBitMask = kCategoryOne;
bodyA.contactTestBitMask = kCategoryTwo;

bodyB.categoryBitMask = kCategoryTwo;
bodyB.contactTestBitMask = kCategoryOne;

Upvotes: 1

Related Questions