What Information Does a planck.js Ray Cast Return?

In planck.js (the 2D JavaScript physics engine based on Box2D), performing a world ray cast requires providing a callback function. This callback executes every time the ray intersects a fixture in the physics world. Instead of returning a static object from the initial world.rayCast() call, planck.js passes four specific pieces of data directly into your callback function upon every intersection.

Arguments Passed to the Callback

When the ray hits a fixture, your callback function is invoked with the following parameters:

world.rayCast(point1, point2, function(fixture, point, normal, fraction) {
  // Your intersection handling logic here
});

Controlling the Ray via Return Values

The callback does not just receive data; it also expects a return value from you. What your callback returns instructs planck.js how to proceed with the remainder of the ray cast:

Return Value Effect on the Ray Cast Common Use Case
fraction Clips the ray to the current intersection point. Finding only the closest object.
1 Continues the ray cast along its original path. Gathering all objects along the line.
0 Terminates the ray cast immediately. Checking if anything is hit.
-1 Ignores the current fixture and continues. Filtering out specific objects (like the shooter).