user1028028
user1028028

Reputation: 6433

SpriteKit colisions not detected

I have 2 SKSpriteNodes in my scene and I would like to detect collisions between them. However this does not work. Here is the relevant code

Node1:

 PSCarNode *newCar = [PSCarNode new];
newCar.size = CGSizeMake(CAR_WIDTH, CAR_HEIGHT);
CGFloat carXval =  - CAR_WIDTH; // start off-screen
newCar.position = CGPointMake(carXval, Yval);
newCar.zPosition = 5;
newCar.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(CAR_WIDTH, CAR_HEIGHT)];
newCar.physicsBody.dynamic = YES;
newCar.physicsBody.categoryBitMask = carCategory;
newCar.physicsBody.contactTestBitMask = frogCategory;
newCar.physicsBody.collisionBitMask  = 0;
newCar.physicsBody.usesPreciseCollisionDetection = YES;
[self addChild:newCar];

Node 2:

    player = [[PSPLAYERNode alloc] init];
[player setPosition: CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))];
[player setSize:CGSizeMake(PLAYER_SIZE, PLAYER_SIZE)];
player.zPosition = 1;
player.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:(3/4)*PLAYER_SIZE];
player.physicsBody.dynamic = YES;
player.physicsBody.collisionBitMask = 1;
player.physicsBody.categoryBitMask = playerCategory;
player.physicsBody.contactTestBitMask = carCategory;
[self addChild:player];

init:

    - (instancetype)initWithSize:(CGSize)size
{
    self = [super initWithSize:size];
    if (self) {
        [self createScene];
        self.physicsWorld.gravity = CGVectorMake(0., 0.); // no gravity
        self.physicsWorld.contactDelegate = self;
        animationInProgress = NO;
    }
    return self;
}

and delegate:

    - (void)didBeginContact:(SKPhysicsContact *)contact
{
    NSLog(@"player hit");
}

Why are there no collisions detected. I can clearly see the car node move over the player node, but nothing is shown in the log.

Upvotes: 0

Views: 42

Answers (1)

CodeSmile
CodeSmile

Reputation: 64477

Because the two objects are in two different categories and their contact bitmasks combined also results in 0.

Just don't set the bitmasks at all until you actually need them to define behavior where two (sets of) bodies either should not contact at all or should generate contact events but not resolve collisions (ie allow them to pass through each other).

You'll find info on how exactly the bitmasks work in the SKPhysicsBody class reference.

Upvotes: 1

Related Questions