Check If a Point Is Inside a Body in Matter.js
This guide explains how to determine whether a specific 2D coordinate
lies within a rigid body in Matter.js. You will learn the two primary
methods for point collision detection: using the high-level
Matter.Query.point utility and utilizing the direct
Matter.Vertices.contains function.
Method 1: Using
Matter.Query.point
The simplest and most common approach is using the
Matter.Query module. The Query.point method
tests a single coordinate against an array of bodies and returns an
array of all bodies containing that point.
To check against a single specific body, wrap it in an array:
// Define your coordinate point
const point = { x: 150, y: 200 };
// Query against your specific body
const collisions = Matter.Query.point([myBody], point);
// Check if the body was returned
const isInside = collisions.length > 0;
if (isInside) {
console.log("The point is inside the body.");
}This method automatically takes rotation, scale, and compound body parts into account.
Method 2: Using
Matter.Vertices.contains
If you want to bypass the query engine or test against the geometry
directly, use Matter.Vertices.contains. This function takes
the body's calculated vertices and the target point:
const point = { x: 150, y: 200 };
// Directly test the point against the body's vertices
const isInside = Matter.Vertices.contains(myBody.vertices, point);
if (isInside) {
console.log("The point is inside the body.");
}Optimizing with Bounds (Optional)
For complex polygons or frequent checks (such as tracking a mouse
cursor on every frame), you can improve performance by performing a
broadphase check using the body's axis-aligned bounding box
(body.bounds) before calculating precise vertex
containment:
function isPointInBody(body, point) {
// Quick bounding box check
if (!Matter.Bounds.contains(body.bounds, point)) {
return false;
}
// Precise polygon check
return Matter.Vertices.contains(body.vertices, point);
}Matter.Query.point already performs this bounding box
optimization internally, making it the recommended solution for most use
cases.