Box2D Raycasts

Box2D has always had a function called TestSegment for colliding segments with shapes, but it really needed conversion into proper raycasts. Check out a Demo.


I’ve implemented this in Flash and C++. It’s the real deal: it uses Box2D’s internal sweep and prune structure for efficient calculations. You should see the best performance gains on the previous naive solutions when doing very long diagonal casts, or when doing a long cast that hits something immediately.

Usage

Pretty simple, really. Either call b2World::Raycast in a similar manner to b2World::Query, or call b2World::RaycastOne in a similar way to b2Shape::TestSegment. The former is for finding multiple shapes, and the latter for the common case of just wanting one shape. It should be pretty obvious, but there are also Doxygen style comments in the code.

In both cases, there is a argument called userData. This is so that you can filter which shapes the ray can hit. By default, passing null means the ray can hit everything, while passing a shape means the ray can only hit things that shape can hit. You can customize it further by overriding the contact filter, which now has an extra method, b2ConcactFilter::RayCollide.

Argument solidShapes determines if rays can hit shapes that they start inside. Fixing this nicely has changed b2Shape::TestSegment‘s return type to an enum.

See the wiki article for more explanation.

Bugs

None known, though it can be fiddly to ensure that rays always collide with what you want. I advise starting from inside a shape, and using solidShapes=false.

Coming features

None

Download

Both the Flash and C++ versions have been checked in.