OK - I'm sure this is a duplicate, and that Whirlwind or KnightOfDragons have posted the solution, but I cannot find it.
I am writing a Space Invader clown in Swift using the Sprite-Kit. The problem is that when an invader bomb hits my ship, the code sometimes detects 2 or 3 collisions, ending the game right away. Here's the 'didBeginContact section, which handles a bomb / ship collision:
case category.bomb.rawValue | category.ship.rawValue: print("Bomb hit ship!") let bomb = contact.bodyA.categoryBitMask == category.bomb.rawValue ? contact.bodyA.node : contact.bodyB.node bomb?.physicsBody?.contactTestBitMask = 0
and when I start the game, I see:
Bomb hit ship! 2 ships left.
after 1 bomb hit (this is correct)
Bomb hit ship! 1 ships left. Bomb hit ship! 0 ships left.
after the 2nd bomb strike (which is wrong).
I have never had a contact that does NOT register, and sometimes (50%?) Works fine. At other times, I saw myself with -4 ships! I am sure this is something obvious / fundamental that I am wrong, though.
My comments regarding setting the TestBitMask contact to 0 for the bomb and ship are obviously wrong. I know that this should not be necessary, as I remove the bomb when contact occurs, so it should not appear again.
How can I guarantee that a contact is processed only once?
==================================
Update: I added 2 print statements to provide additional debugging information:
print("bodyA is \(contact.bodyA.node!.name)") print("bodyB is \(contact.bodyB.node!.name)")
This is after the let bomb = contact.bodyA.category ... instruction and now I get:
Bomb hit ship! bodyA is Optional("bomb") bodyB is Optional("playerShip") 1 ships left.
after 1 bomb hit and:
Bomb hit ship! fatal error: unexpectedly found nil while unwrapping an Optional value
after hitting the 2nd bomb. So, after the second collision, body A is zero, so I donβt understand why the Sprite-Kit actually detected the collision?
Any ideas?