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 – setting up the world step loop


We will make the world time advance by carrying out the following steps:

  1. In order to advance the world step, we have to call the step function in the world instance periodically. We used setTimeout to keep calling the step function. Put the following function in our JavaScript logic file:

    function updateWorld() {
      // Move the physics world 1 step forward.
      carGame.world.Step(1/60, 10, 10);
    
      // display the build-in debug drawing.
      if (shouldDrawDebug) {
        carGame.world.DrawDebugData();
      }
    }
  2. Next, we will set up an interval in the initGame method:

    setInterval(updateWorld, 1/60);
  3. We will again simulate the world in a browser. The box is created at the initialized position and falls on the ground correctly. The following screenshot shows the sequence of a box dropping on the ground:

What just happened?

We have advanced the time of the world. Now, the physics library simulates the world in a frequency of 60 times per second. In the game loop...