0

So I am using the didBeginContact method to detect the collision between the physics bodies of a bullet and other objects in my scene using the block of code below:

-(void)didBeginContact:(SKPhysicsContact *)contact
{
    uint32_t collision = (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask);

    if (collision == (WWPhysicsCategoryOther | WWPhysicsCategoryBullet)) {
        [_bullet removeFromParent]
    }
}

When one bullet is on the screen, the bullet is removed. However, like many shooting games, the player is allowed to fire bullets repetitively. I find that when more than one bullet is on screen, not all of them are removed after contact. How can I ensure that every bullet is immediately removed right after a collision?

wtivie05
  • 45
  • 2
  • 2
    I suggest you identify which contact body (A or B) is the bullet and then remove the corresponding node from its parent. For example, [contact.bodyA.node removeFromParent]; – 0x141E Dec 20 '14 at 04:50
  • 2
    _bullet seems to be a pointer to only a single node. You need to find the node which corresponds to the physicsbody in the contact delegate itself. Here's how: http://stackoverflow.com/a/20604762/2043580 – ZeMoon Dec 20 '14 at 06:20
  • Thanks both for the responses. Very helpful! – wtivie05 Dec 20 '14 at 15:58

1 Answers1

1

0x141E and ZeMoon comments are correct.

_bullet is probably a pointer to a specific node, therefore, on collision detection, the bullet node that collides is probably not always the one that has that pointer to (which means that could be that when collision happens, some other bullet on screen is being removed).

A better and more 'correct' way of doing that is, on didBeginContact: identify which contact body is the bullet, and using its node property, remove it from its parent.

Something along the following example should work-

-(void)didBeginContact:(SKPhysicsContact *)contact
{
    uint32_t collision = (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask);

    if (collision == (WWPhysicsCategoryOther | WWPhysicsCategoryBullet)) {  

        SKNode *bulletNode = (contact.bodyA.categoryBitMask == WWPhysicsCategoryBullt) ? contact.bodyA.node : contact.bodyB.node;

        [bulletNode removeFromParent]
    }
}
AMI289
  • 1,098
  • 9
  • 10