Stop your game when your object is stuck by the Physics Engine in Corona SDK

In this small post I will share some code which might be useful when your developing a game which uses the physics engine like in my personal RollyBear Project.

The problem I have been trying to solve was to prompt the game-over screen when the physics engine positions RollyBear (or the object) in a state that the object is not affected anymore by the physics. For the player this means that (s)he is stuck and need to re-start the level. I think from a design point of view it would be nicer when the game can control for this situation and prompt the game-over screen (or try again screen).

I achieved this by checking for the .isAwake state provided by the Corona SDK. When “true” this means the object is still affected by the physics engine, when false the object is not affected anymore by the physics engine.

rollybearstuck

So create a function which checks every 3 seconds if the object.isAwake == false.
When the object is not anymore “awake” then we stop the timer, pause the physics engine and show a try-again overlay. Of course, it’s up to you to decide what needs to happen when your object is not affected anymore by the physics engine. I used 3 seconds as interval, in case the object starts to move again for whatever reason.

function evaluateAwake() 
    if (rollybear.isAwake == false) then
       timer.cancel(objectAwake) 
       physics.pause()
       storyboard.showOverlay( "gameoveroverlay" ,{effect = "fade"  ,  params ={curLevel = currentLevel}, isModal = true} )
       rollybear:pause()
    end   
end 

objectAwake = timer.performWithDelay(3000, evaluateAwake, 0) -- check if rollybear is moving every 3 second

As you can see it is very simple, but effective.