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 – drawing the physics world into the Canvas


Carry out the following steps to draw the useful debug view:

  1. First, open the box2dcargame.js JavaScript file:

    var shouldDrawDebug = false;
  2. Add a function that draws the debugging lines:

    function showDebugDraw() {
      shouldDrawDebug = true;
    
      //setup debug draw
      var debugDraw = new b2DebugDraw();
      debugDraw.SetSprite(document.getElementById('game').getContext('2d'));
      debugDraw.SetDrawScale(pxPerMeter);
      debugDraw.SetFillAlpha(0.3);
      debugDraw.SetLineThickness(1.0);
      debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
    
      carGame.world.SetDebugDraw(debugDraw);
    
      carGame.world.DrawDebugData();
    }
  3. Add a showDebugDraw function call at the end of the initGame method:

    showDebugDraw();
  4. Now, reopen the game in a browser, and we should see the outline of the ground body in the canvas, as shown in the following screenshot:

What just happened?

We have just defined a method that asks the Box2D engine to draw the physics bodies...