1

Like many game programmers in SpriteKit, I use collision detection between certain objects to call methods or set properties. However, sometimes my actions happen twice in a collision. Here is an example from inside my didBeginContact method:

uint32_t collision = (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask);

if (collision == (WWPhysicsCategoryShip | WWPhysicsCategoryWeapon)) {
    SKNode *weapon = (contact.bodyA.categoryBitMask == WWPhysicsCategoryWeapon) ? contact.bodyA.node : contact.bodyB.node;
    [weapon removeFromParent];

    _localPlayerHP = _localPlayerHP - 5;
    NSLog(@"My Health is now at %i.", _localPlayerHP);
}

You'll notice that my ship's health is decreased by 5 and the enemy weapon that contacted the ship is removed. But when testing the game, I find that my ship's health is often reduced by 10, in increments of 5 (indicating that my decrease health method has fired more than once). I find this odd since the weapon is removed on first contact. How can I ensure that my health is only decreased by 5 once per contact?

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
wtivie05
  • 45
  • 2
  • 1
    how do you create the bodies? if you use body with polygon or texture, it's quite possible that the shape is broken up internally into convex shapes, and collision events are generated for each shape, so you can get multiple events for a single Body – CodeSmile Feb 01 '15 at 11:35

1 Answers1

0

Maybe you can try this

if weapon.parent != nil {
     _localPlayerHP = _localPlayerHP - 5;
}

This question talks about another way by making the ship invulnerable for a few seconds after it gets hit.

didBeginContact is being called multiple times for the same SKPhysicsBody

Community
  • 1
  • 1
rakeshbs
  • 24,392
  • 7
  • 73
  • 63