How to Use Matter.Query.point in Matter.js

This article explains how to detect physics bodies at specific 2D coordinates in Matter.js using the Matter.Query.point method. You will learn the correct syntax, how to retrieve the active bodies from your physics simulation, and how to implement a working example commonly used for mouse clicks, touch interactions, or spatial point checks.

The Matter.Query.point Method

Matter.js provides the Matter.Query module for performing spatial queries against physics bodies. To check for collisions or intersections at a single coordinate, use Matter.Query.point().

The method accepts two arguments:

  1. bodies (Array): The list of Matter.Body objects you want to test against.
  2. point (Object): A coordinate object in the format { x: Number, y: Number }.

It returns an Array containing all bodies that overlap the specified point. If no bodies overlap, it returns an empty array ([]).

Implementation Example

To query bodies within an active world, first retrieve all bodies using Matter.Composite.allBodies(), then pass them along with your target coordinates into Matter.Query.point():

// 1. Define the point to check (e.g., mouse click or screen coordinate)
const checkPoint = { x: 400, y: 300 };

// 2. Retrieve all bodies currently active in the physics world
const allBodies = Matter.Composite.allBodies(engine.world);

// 3. Query for bodies intersecting the point
const foundBodies = Matter.Query.point(allBodies, checkPoint);

// 4. Handle the results
if (foundBodies.length > 0) {
    foundBodies.forEach((body) => {
        console.log("Body clicked or intersected:", body.id, body.label);
    });
} else {
    console.log("No bodies found at the given point.");
}

Handling Mouse and Touch Events

A standard use case is detecting which body a user clicked on an HTML canvas:

canvas.addEventListener('click', (event) => {
    const rect = canvas.getBoundingClientRect();
    const mousePosition = {
        x: event.clientX - rect.left,
        y: event.clientY - rect.top
    };

    const bodies = Matter.Composite.allBodies(engine.world);
    const clickedBodies = Matter.Query.point(bodies, mousePosition);

    if (clickedBodies.length > 0) {
        const topBody = clickedBodies[0]; // The first detected body
        Matter.Body.applyForce(topBody, topBody.position, { x: 0, y: -0.05 });
    }
});

Key Considerations