Currently, my game has a main update loop that is scheduled to run every frame. The loop does something like:
for each entity pair
check collision between entities
for each entity
update each entity
This works fine for the most part. However, certain entities may create other entities during its update call. For example, I have some enemy entities that fire bullets, and these bullets are created during the update call for the enemy entity.
The update call for an enemy looks like:
create a bullet entity and add it to the scene
update own position
Because of this, I'm occasionally seeing bullets colliding with the enemies that fired them. This is because once the bullet has been created, it hasn't yet had a chance to update its position. Meanwhile, the enemy updates its position, and collides with the bullet.
What's strange to me is that this is non-deterministic behavior. On the surface, it seems like these collisions should always happen, since:
a bullet is created
the enemy is moved
the next game update detects collision
the bullet is moved
However, I'm only seeing these collisions happen once in a while. It seems like what may be happening more often is:
a bullet is created
the NEXT game update runs
no collisions detected
the bullet is moved
the enemy is moved
That is, some game update calls are being made before previous ones have finished. It seems like this is something that one should expect and code for (although I didn't realize it until now), due to the event-based scheduling nature of cocos2d.
What's a standard way of going about doing collision detections and position updates in the game while avoiding funky, non-deterministic behavior like this that may crop up due to overlapping, interleaved update calls?