Trying to make a stationary turret fire at a moving enemy (tower defense game).
static const uint32_t towerCategory = 0x1 << 0;
static const uint32_t creepCategory = 0x1 << 1;
If the above is right, the towerCategory should have the lower category number correct?
tower.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:80];
tower.physicsBody.dynamic = YES;
tower.physicsBody.categoryBitMask = towerCategory;
tower.physicsBody.contactTestBitMask = creepCategory;
tower.physicsBody.collisionBitMask = 0;
This should set the tower node to be in the towerCategory and react to contact between the creep moving into range (range being the 80 radius physics body). Since I also don't want the tower or creep to push each other, I set the collision to 0.
baddie.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:baddie.size];
baddie.physicsBody.dynamic = YES;
baddie.physicsBody.categoryBitMask = creepCategory;
baddie.physicsBody.contactTestBitMask = towerCategory;
baddie.physicsBody.collisionBitMask = 0;
Same thing for the enemy. I switch the category and contact bitMask though since this one should be a creep, and it contacts the tower. Still no collision though so set it to 0.
SKPhysicsBody* firstBody;
SKPhysicsBody* secondBody;
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
{
firstBody = contact.bodyA;
secondBody = contact.bodyB;
}
else
{
firstBody = contact.bodyB;
secondBody = contact.bodyA;
}
if ((firstBody.categoryBitMask & towerCategory) != 0 &&
(secondBody.categoryBitMask & creepCategory) != 0)
{
[secondBody.node removeAllActions];
}
I am pretty sure the didBeginContact function is where things are failing. Since towerCategory is lower than creepCategory, it should always be placed in firstBody if my code is correct. Then when the creep moves into contact range it should remove all actions from it and stop on the tracks. However he just keeps moving through. Can someone point out what I am missing?
contactTestbitMask
to bodyB's categorybitMask - you don't need to set bodyb to contact bodyA. – Steve Ives