HTML and CSS Reference
Adding Physics with Box2D
A bunch of static elements hanging out in space isn't a whole lot of fun. To make things more interactive
and save the hassle of trying to figure out collisions on arbitrary convex polygons, Quintus adds support for a
Box2D, created by Erin Catto, is written in C++, but a few adventurous souls manually created an Ac-
tionScript 3.0 port called Box2DFlash (available at http://box2dflash.sourceforge.net/ ) to allow Flash deve-
lopers to use Box2D. A few other adventurous folks, taking advantage of the similarities between ActionScript
the SVG code already written is straightforward.
There is no full documentation for Box2Dweb, but that's because it shares the same definitions as box2d-
The SVG code in this chapter was implemented specifically with the idea to add in a physics engine, but it
stands to reason that a Canvas game might also want to do the same. For that reason, the physics functionality
of Quintus is created as a set of components rather than as classes extending SVGSprite and SVGStage. The
basic Canvas Sprite class and default Stage wouldn't use the physics components without adding in support for
rotated sprites, but that's something that could be added to the base class easily.
Understanding Physics Engines
Before getting into the details of integrating a physics engine, you need to understand what a physics engine
The reason for integrating a physics engine into the system is that the way objects interact in the real world
is quite involved. If you want to accurately simulate the behavior of a ball flying into a stack of blocks in 2-D
space, which results in the tower tumbling over and blocks spinning and careening off each other, you'd be in
for some work.
The first challenge would be to calculate pixel-perfect collisions between the various boxes and the ball. With
boxes rotated at various angles, the simple box collision detection from earlier chapters would fall far short.
The next challenge would be to accurately simulate the behavior after a collision happens: Do the two boxes
bounce off each other? Does a box slide on the ground or stick because of friction? How should an arbitrary
polygon rotate when it's hit?
Physics engines handle both of these challenges for you. Your job is to define the shape and physical proper-
ties of the bodies that make up the simulation. From that point you can hand those details off to the physics, and
tell it to advance the simulation by 1/60th of a second and give you the new angles and positions of objects. The
physics engine can take care of updating objects according to their velocities and any forces (including gravity)
acting on them and take care of properly resolving any collisions and interactions.