Slicing things with Box2D

I have been playing with Box2DWeb and made a little slicing demo. Drag a line through one of the shapes and it breaks into pieces that keep falling and bumping into everything else. It is surprisingly entertaining for something that does not really have a game attached to it yet.

Box2D handles the physics. The slicing code casts a ray in both directions to find where the cut enters and leaves a polygon, then sorts the vertices onto the two sides. Each new piece gets its own body centered on its centroid. I carry over the old body’s linear and angular velocity before removing it, so the pieces do not suddenly stop moving.

The tricky part is turning a line drawn on the canvas into two valid shapes rather than just drawing a crack across the original one. I may make a game out of this eventually. For now, cutting up the pile is a pretty good tech demo.

Try the slicing demo