worldWalls

This is an example of surrounding `world` of canvas with walls.

by Tatsuya Suzuki

HTML

<script src="https://googledrive.com/host/0B-jdnZOJbr7XUkgybU1zYUs0dG8/Box2dWeb-2.1.a.3.js"></script>
<script src="https://googledrive.com/host/0B-jdnZOJbr7XUkgybU1zYUs0dG8/b2LoadAllClasses.js"></script>
<canvas id='canvas' width='500px' height='500px' style='background-color: beige;'></canvas>

CSS

/*
* This is an example of surrounding `world` of canvas with walls.
*
* Walls are generated within class, 'worldWalls', where you can specify which edge
* of world you want to have a wall with binary`trbl`.
* 
* See class document how to specify its arguments.
* 
/

JavaScript

var world = new b2World(new b2Vec2(0, 100), true);
var fixDef = new b2FixtureDef;
var bodyDef = new b2BodyDef;
var canvas = document.getElementById('canvas')
var context = canvas.getContext('2d');

function debugDraw(world, context) {
  var debugDraw = new b2DebugDraw();
  debugDraw.SetSprite(context);
  debugDraw.SetDrawScale(10.0);
  debugDraw.SetFillAlpha(0.5);
  debugDraw.SetLineThickness(1.0);
  debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
  world.SetDebugDraw(debugDraw);

  return debugDraw;
}
var debugDraw = new debugDraw(world, context);
function Ball(position) {
  var fixDef = new b2FixtureDef;
  var bodyDef = new b2BodyDef;

  bodyDef.type = b2Body.b2_dynamicBody;
  bodyDef.position = position;
  fixDef.shape = new b2CircleShape(5.0);
  fixDef.restitution = 1.1;

  var ball = world.CreateBody(bodyDef);
  ball.CreateFixture(fixDef);
  return ball;
}

var ball1 = new Ball(new b2Vec2(10, 10));
var ball2 = new Ball(new b2Vec2(20, 1));
var ball3 = new Ball(new b2Vec2(29, 10));

// trbl stands for Top Right Bottom Left. It's a binary string to set which
// edge of the world has a wall. 
//
// e.g.
//  '0111' generate walls on right, bottom and left.
//  '0010' generate a wall only on bottom.
// 
// To access a wall from out side the class, refer its property;
//   var walls = new worldWalls(debugDraw.GetDrawScale(), canvas, '0111');
//   walls.right.restition = 10;
function worldWalls(scale, canvas, trbl) {
  // Define walls and set null to avoid `undefined`
  this.top = null;
  this.right = null;
  this.bottom = null;
  this.left = null;

  var WIDTH = canvas.width / scale;
  var HEIGHT = canvas.height / scale;
  var THICKNESS = 0.1;
  var trblBin = parseInt(trbl, 2);

  var fixDef = new b2FixtureDef;
  var bodyDef = new b2BodyDef;

  bodyDef.type = b2Body.b2_staticBody;
  fixDef.shape = new b2PolygonShape;
  fixDef.restitution = 0.5;

  if(trblBin & parseInt('1000', 2)){
    fixDef.shape.SetAsBox(WIDTH / 2, THICKNESS);
   ...