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
});fixture: The specificFixtureobject that the ray intersected. Through this, you can access the body it belongs to, its user data, or its collision filters.point: AVec2object indicating the exact position in world coordinates where the ray intersected the fixture’s shape.normal: AVec2object representing the unit normal vector pointing away from the surface of the shape at the exact point of intersection.fraction: A number between0and1indicating the fractional distance along the ray where the intersection occurred (relative to the total length betweenpoint1andpoint2).
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). |