Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I draw my Box2D world using HTML5 Canvas instead of Debug Draw?

I know HTML5 canvas fairly well, I know the basics and animation using loops etc.

Demo I'm working with: (click to make shapes) http://henry.brown.name/experiments/box2d/example-canvas.html

What I'm not very familiar with is Box2D. I'm using the Box2DWeb port, I heard it was newer than Box2D-js, I'm not sure which is best.

I know how to initialize the 'world' and I can place objects in the world. I then use Step to animate the world - however to display it on the screen so far I've only been able to get it working with debug draw as it basically does everything for you.

Instead of using debug draw I'd like to use canvas to draw, for example a car instead of just a square. How do I attach the physics of a square to the image of a car? I just can't get my head around integrating canvas with Box2D.

Any tips will be massively appreciated!

Thanks

like image 739
Sabai Avatar asked Sep 03 '11 15:09

Sabai


1 Answers

I spent the last few days trying the same thing. I found Jonny Strömberg's tutorial, which is not super detailled but by analyzing the code I found how he retrieves the body's position:

var b = world.GetBodyList()

GetBodyList() seems to be an iterative Array, so the next body is accessible through b.m_next.

You can then use

b.GetPosition().x
b.GetPosition().y
b.GetAngle()

to retrieve the body's coordinates.

EDIT: this code is for the Box2dweb library, which I found better documented than Box2djs

like image 135
Thibaut Avatar answered Sep 25 '22 00:09

Thibaut