“Flying Space Rocks” progress – fix for addBody after collision event in CoronaSDK

I have been building a simple Astroid clone as some of you know. Well I found a bug that really stopped me in my tracks. My understanding is that it’s a bug with the Box2d logic that Corona uses for it’s physics engine.

During a collision event you basically crash the application if you try to set any properties on any of the bodies that are being updated by the physics engine. I was able to get a crash by trying to call addBody and also by trying to do something simple like setting X and Y properties on a body that the physics engine was trying to update during the collision.

The fix really is pretty simple and I consider more of a “hack” than anything. You basically have to create an enterframe event and call your logic with in the enterframe function. This basically allows the physics update to complete and then you can act on the objects within the physics engine on the next frame. As you will see I create a local function with in the collision event that runs and then also removes the enterframe that we create as soon as we are done running our logic.

If anyone has a better solution please feel free to post in the comments.

The things that where crashing the app that are now fixed where the following. When a missel collides with a rock I wanted to create smaller rocks and then move the missel that was just used off screen so that it does not collied with any more objects till it is shot from the spaceship again.