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 – putting a dynamic box in the world


Carry out the following steps to create our first dynamic body:

  1. Open our JavaScript file and add the following box creation code to the page loaded event handler. Place the code after the createGround function:

    // temporary function
    function createBox() {
      var bodyDef = new b2BodyDef;
      var fixDef = new b2FixtureDef;
    
      bodyDef.type = b2Body.b2_dynamicBody;
      bodyDef.position.x = 50/pxPerMeter;
      bodyDef.position.y = 210/pxPerMeter;
    
      fixDef.shape = new b2PolygonShape();
      fixDef.shape.SetAsBox(20/pxPerMeter, 20/pxPerMeter);
    
      var body = carGame.world.CreateBody(bodyDef);
      body.CreateFixture(fixDef);
    
      return body;
    }
  2. We need to call our newly created createBox function. Place the following code after we call the createGround function inside initGame.

  3. Now, we will test the physics world in a browser. You should see that a box is created at the given initial position. However, the box is not falling down; this is because we still have to...