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 – creating a ground in the world


Carry out the following steps to create a static ground:

  1. Open the box2dcargame.js JavaScript file.

  2. Define the following pxPerMeter variable in the file; this is the unit setting in the Box2D world:

    var pxPerMeter = 30; // 30 pixels = 1 meter
  3. Add the following function to the end of the JavaScript file; this creates a fixed body as the playground:

    function createGround() {
      var bodyDef = new b2BodyDef;
      var fixDef = new b2FixtureDef;
    
      bodyDef.type = b2Body.b2_staticBody;
      bodyDef.position.x = 250/pxPerMeter;
      bodyDef.position.y = 370 /pxPerMeter;
    
      fixDef.shape = new b2PolygonShape();
      fixDef.shape.SetAsBox(250/pxPerMeter, 25/pxPerMeter);
      fixDef.restitution = 0.4;
    
      // create the body from the definition.
      var body = carGame.world.CreateBody(bodyDef);
      body.CreateFixture(fixDef);
    
      return body;
    }
  4. Call the createGround function in the initGame function after we have created the world as follows:

    createGround();
  5. As we are still defining...