Saturday, December 11, 2010

Box2D and DebugDraw

It is very useful to have a physics engine such as Box2D running if you want your game to be very interactive and mega awesome, but physics can be a bit of a pain to implement in your engine or game!
Lucky ours that we Box2D library (http://www.box2d.org/) provides a debug drawing interface!

What is that? When the world function "Step" is called, the physic calculations will happen, and the physic shapes will be updated with new positions, rotations and such.
After this positions are ready, you can make a call to DebugDraw so everything is renderered in the screen without worrying about game sprites or anything!

Hows does it work exactly? Based on virtual calls, of course!
The physics world object has a pointer to a b2DebugDraw object, and calls his virtual functions when it wants to draw something in the screen!

What is a virtual function? Well, its a function declared with the prefix "virtual" inside a class. This function can be called normally and even do some code..
The magic happens when you derive your own class from b2DebugDraw and override those virtual methods just by declaring and defining functions with the same name! You can define them with rendering code, OpenGL , for instance!

Then, you can tell Box2D to use your DebugDraw instead of the native one, and voila, everything appears on the screen, because Box2D will call the functions internally!

You can look at a example code here:
Box2D and Debug Drawing Explained

Enjoy boxing : )

1 comment: