Romain Beaudon

Linerider clone with HTML5 Canvas and Box2D JS

Dog Sled is a little weekend project game hacked with HTML5 Canvas, Javascript and Box2D :

Dog Sledsource

Code details

Initialisations

1
2
3
4
5
6
7
8
9
//...
dog_initcanvas();
dog_initsound();
dog_events(); //mouse and keyboard
dog_initworld();
dog_setupcollisions();
dog_initdraw();
dog_update();
//...

Collisions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//...
function dog_setupcollisions()
{
   var listener = new Box2D.Dynamics.b2ContactListener;
   listener.BeginContact = function(contact) {
      //if the dog touch the line we add a flag
      //...
   listener.PreSolve = function(contact) {
      //if the dog eats a bone there's no collision
      //...
   listener.PostSolve = function(contact, impulse) {
      //if the dog touch his house
      //and sounds...
      //...

Main loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//...
function dog_update()
{
  window.requestAnimationFrame(dog_update);

  world.Step(
      1 / 60,   //frame-rate
      10,      //velocity iterations
      10      //position iterations
  );

  world.ClearForces();
  canvas_draw(); //graphics
}
//...
function canvas_draw()
//...
//we iterate through all the bodies
for(body = world.GetBodyList(); body; body = body.GetNext()) {
   //...
   //we use the User Data field to know what to draw
  switch(body.GetUserData()) {
      case 'line':
//...

I used¬†Box2DWeb, a javascript port of box2d 2.1. It lacks features like rope joint but I realized it too late… More up to date ports i didn’t try :¬†

Have fun!

Good tutorials : Seth Ladd’s blog