Book Image

HTML5 Game Development by Example: Beginner's Guide

By : Seng Hin Mak
Book Image

HTML5 Game Development by Example: Beginner's Guide

By: Seng Hin Mak

Overview of this book

Table of Contents (18 chapters)
HTML5 Game Development by Example Beginner's Guide Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
9
Building a Physics Car Game with Box2D and Canvas
Index

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:

  1. Again, we only need to change the JavaScript file. Open the box2dcargame.js JavaScript file in a text editor.

  2. 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);
      }
    }
  3. 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, 25, 0);
    
      /...