Time for action – restarting the game while pressing the R key
We will assign the R key as the restart key for our game. Now, let's perform the following set of steps:
- Again, we only need to change the JavaScript file. Open the
box2dcargame.js
JavaScript file in a text editor. - We need a function to remove all the bodies:
function removeAllBodies() { // loop all body list to destroy them for (var body = carGame.world.GetBodyList(); body != null; body = body.GetNext()) { carGame.world.DestroyBody(body); } }
- We move the create world, ramp, and the car code into a function named
restartGame
. They were originally in the page loaded handler function:function restartGame() { removeAllBodies(); // create the ground createGround(250, 270, 250, 25, 0); // create a ramp createGround(500, 250, 65, 15, -10); createGround(600, 225, 80, 15, -20); createGround(1100, 250, 100, 15, 0); // create a destination ground carGame.gamewinWall = createGround(1200, 215, 15,...