TazmanNZL
TazmanNZL

Reputation: 392

SpriteKit didBeginContact issue with 2 non dynamic bodies

I'm trying to create a game with blocks that can be moved around they all belong to the same categoryBitMask. The didBeginContact does not fire unless I set the physicsBody to dynamic. How can I detect collision between two blocks that belong to the same category?

Code for generating blocks:

float blkX = 34;
    float blkY = 64;

    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 6; j++){
            block = [SKSpriteNode spriteNodeWithImageNamed:blocksArray[(arc4random()%5)]];
            block.position = CGPointMake(blkX, blkY);
            block.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:block.size];
            block.physicsBody.usesPreciseCollisionDetection = YES;
            block.physicsBody.dynamic = NO;
            block.physicsBody.categoryBitMask = blockCategory;
            block.physicsBody.contactTestBitMask = blockCategory;
            block.physicsBody.collisionBitMask =  blockCategory;
            [block setName:@"block"];
            [_bgLayer addChild:block];
            blkX += 48;
        }
        blkX = 34;
        blkY += 48;
    }

I am using the SKPhysicsContactDelegate and have the following two lines in my init method:

self.physicsWorld.contactDelegate = self;
self.physicsWorld.gravity = CGVectorMake(0.0, 0.0);

My didBeginContact method:

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

firstBody = contact.bodyA;
secondBody = contact.bodyB;

NSLog(@"We Collided!");

}

Any help appreciated. Thanks!

Upvotes: 2

Views: 110

Answers (1)

TazmanNZL
TazmanNZL

Reputation: 392

I did come up with something that does work for those in a similar situation:

In my touchesBegan method I set the block being moved to be Dynamic which does fire the didBeginContact. Here is my touchesBegan method:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    self.selectedNode = [self nodeAtPoint:[[touches anyObject] locationInNode:self]];
    [self.selectedNode.physicsBody setDynamic:YES];
}

Then you turn it off again in the touchesEnded method.

I also set the block.physicsBody.collisionBitMask = 0 which allows the block to move through other blocks. If this helps at least one other person then it was worth asking the question!

Upvotes: 2

Related Questions