Simple jar of balls
by anup1986
HTML
<script src="http://chusete.es/demos/box2d/lib/box2djs.min.js"></script>
<canvas id="canvas" width="200" height="250"></canvas>
CSS
#canvas {
position:absolute;
top:0;
left:10px;
background-color:#F5F5F5;
}
JavaScript
var world;
var ctx;
var canvasWidth;
var canvasHeight;
function createWorld() {
// Finish defining the boundary coordinates
// It is preferable to spend before falling short
var worldAABB = new b2AABB();
worldAABB.minVertex.Set(-1000, -1000);
worldAABB.maxVertex.Set(1000, 1000);
// Define the gravitational vector. And indeed,
// Can be a lateral G :)
var gravity = new b2Vec2(0, 300);
// Also indicate that the elements can "sleep"
// When in repose.
var doSleep = true;
// And we can create the world
world = new b2World(worldAABB, gravity, doSleep);
// We now call createGround, and we will create a floor
createGround(world);
createWalls(world);
//Finally, we return the world
return world;
}
function createGround(world) {
//We define a shape. In this case is a square shape
var groundSd = new b2BoxDef();
// We set a size 400x30
groundSd.extents.Set(200, 1);
// And we put a minimum factor of restitution (elasticity).
groundSd.restitution = 0.0;
// Now create the object itself
var groundBd = new b2BodyDef();
// Add the shape of the object
groundBd.AddShape(groundSd);
// We assign their coordinates
groundBd.position.Set(200, 249);
// And add the object to the world
return world.CreateBody(groundBd);
}
function createWalls(world){
var leftWallShape = new b2BoxDef(),
rightWallShape = new b2BoxDef();
leftWallShape.extents.Set(1, 250);
rightWallShape.extents.Set(1, 250);
leftWallShape.restitution = 0.0;
rightWallShape.restitution = 0.0;
var leftWallObj = new b2BodyDef();
var rightWallObj = new b2BodyDef();
leftWallObj.AddShape(leftWallShape);
rightWallObj.AddShape(rightWallShape);
leftWallObj.position.Set(1, 1);
rightWallObj.position.Set(199, 1);
world.CreateBody(leftWallObj);
return...