Matter.js Raycast Return Value Explained
In the Matter.js 2D physics engine, raycasting is executed using the
Matter.Query.ray method to detect bodies along a line
segment. This article covers the exact data structure returned by the
raycast function, the specific properties included in each collision
object, and how to interpret these results in your game or simulation
logic.
The Return Value: An Array of Collisions
The
Matter.Query.ray(bodies, startPoint, endPoint, [rayWidth])
method returns an array of collision objects.
If no bodies intersect the path between startPoint and
endPoint, the method returns an empty array
([]). If one or more bodies intersect the ray, the array
contains one collision object for each detected intersection.
Structure of the Collision Object
Each element in the returned array represents a collision hit and contains the following key properties:
body: A reference to the Matter.jsBodythat the ray intersected.point: A vector{ x, y }representing the coordinates of the collision point where the ray entered the body.normal: A normalized vector{ x, y }perpendicular to the surface of the body at the point of intersection. This is useful for calculating bounce angles, reflections, or surface orientation.tangent: A vector{ x, y }parallel to the surface of the body at the point of impact.penetration: A vector{ x, y }indicating the depth and direction of the ray's penetration into the target body.supports: An array of support vectors on the body that define the contact points.
Key Considerations When Handling Results
Unsorted Results
Matter.js does not automatically sort the returned collisions by
distance from the startPoint. If you need to find the first
object hit (the closest intersection), you must iterate through the
returned array and calculate the Euclidean distance between
startPoint and each result's point
property:
const hits = Matter.Query.ray(allBodies, startPoint, endPoint);
let closestHit = null;
let minDistance = Infinity;
for (const hit of hits) {
const dx = hit.point.x - startPoint.x;
const dy = hit.point.y - startPoint.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < minDistance) {
minDistance = distance;
closestHit = hit;
}
}Sensor Bodies
By default, Matter.Query.ray tests against all bodies
passed into its bodies parameter, including sensor bodies
(isSensor: true). If you do not want non-colliding triggers
to register in your raycast, filter them out before passing the body
list into the function or ignore them while processing the returned
array.