SpriteKit: didBeginContact is called multiple times

    How to handle SKPhysicsContactDelegate’s didBeginContact method being called multiple times. While working on an iOS game I came across the didBeginContact method and it’s confusing wording, I definitely learned allot by experimenting and reading. I hope to share some useful knowledge. 

    The confusing part here is the words begin and first. In practice two physics bodies touch more than one time. My guess is that when two physics bodies touch for a second or two the Game Loop (called multiple times per second) counts the one touch as multiple smaller touches. Without getting too philosophical, what exactly is the definition of a touch ? A computer needs an exact definition, including the duration. I suspect that a touch is not one second long, its actually a couple of milliseconds long. This is why we need to assume that the didBeginContact method will be called multiple times per “human touch”. What we consider a touch might be different than what SpriteKit considers a touch.  

    Here is a short video of the game that I’m working on. When the log hits the hippo, the didBeginContact method is called about 3-6 times. 


Pitfall: 

Most programmers assume that didBeginContact() is called once. They might decrement or increment health and then wonder why their game logic is acting up. I don’t blame the programmer, I think the documentation could be more specific. 

Solution:

    In most games removing an object from the scene is not efficient. The reason being that you will need to re-create it and that is expensive. I created an array of logs named unusedLogs, to prevent unnecessary initialization of new logs.

    I adapted to didBeginContact() being called multiple times by checking if the log in question is not in the unusedLogs array. If the log is in the unusedLogs array it means that I have already went through the if statement and decremented the hippo’s health. If that didn’t make sense take a look at a piece of my code. 

addPow() basically adds the POW special effect that you can see in the video demo.