TheM00s3
TheM00s3

Reputation: 3711

SkSpriteNode collision not being detected

Im using Sprite Kit to detect collision between two objects. Here is how I define their bitmasks.

static const uint32_t puffinCategory = 0x1 << 0;
static const uint32_t planeCategory = 0x1 << 1;

Here is my code as to how setup the puffins and planes physics body. For puffin

SKSpriteNode *PuffinNode = [[SKSpriteNode alloc]initWithImageNamed:@"puffin"];
    PuffinNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:PuffinNode.size];
    PuffinNode.physicsBody.usesPreciseCollisionDetection = YES;
    PuffinNode.physicsBody.categoryBitMask = puffinCategory;
    PuffinNode.physicsBody.dynamic = NO;
    PuffinNode.physicsBody.collisionBitMask = puffinCategory;
    PuffinNode.physicsBody.contactTestBitMask = planeCategory;


    [PuffinNode setZPosition:1.5];

For Plane

SKSpriteNode *planeSpriteNode = [[SKSpriteNode alloc]initWithImageNamed:planeStringFileName];
planeSpriteNode.position = CGPointMake(0, self.view.frame.size.height*-1);
planeSpriteNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:planeSpriteNode.size];
planeSpriteNode.physicsBody.usesPreciseCollisionDetection = YES;
planeSpriteNode.physicsBody.categoryBitMask = planeCategory;
planeSpriteNode.physicsBody.dynamic = NO;
planeSpriteNode.physicsBody.collisionBitMask = puffinCategory;
planeSpriteNode.physicsBody.contactTestBitMask = puffinCategory;

Here is my implementation of the delegate method didBeginContact:

-(void)didBeginContact:(SKPhysicsContact *)contact{
    NSLog(@"collission method run");
    SKPhysicsBody *firstBody, *secondBody;
    if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask){
        firstBody = contact.bodyA;
        secondBody = contact.bodyB;
    }else{
        firstBody = contact.bodyB;
        secondBody = contact.bodyA;
    }

    if ((firstBody.categoryBitMask & puffinCategory) != 0 && (secondBody.categoryBitMask & planeCategory) != 0 ){
        NSLog(@"collission occured");
    }   
}

Im not seeing the method logging if it is called, nor do I see a log when the two sprites collide.

Upvotes: 0

Views: 183

Answers (2)

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36401

Some problems :

1) Did you set the SKScene's physicsWorld.contactDelegate ? 2) Both of your nodes have no dynamic. If you want them to interact in the physics world you should make them under physics laws. One of them at least must be dynamic. 3) Your collisionBitMask are not well set.

Upvotes: 0

user4233369
user4233369

Reputation:

You set

PuffinNode.physicsBody.dynamic = NO;

and

planeSpriteNode.physicsBody.dynamic = NO;

two static bodies cannot collide, at least one should be dynamic

Upvotes: 2

Related Questions