How to Find a Body by ID in Matter.js
Finding a specific rigid body by its identifier is a common task when
updating, styling, or removing elements in a Matter.js simulation.
Matter.js automatically assigns a unique numerical id
property to every created body, though you can also set your own. To
retrieve a body using this ID from the simulation world, you can either
use the built-in Matter.Composite.get method or search the
flattened list of all bodies using standard JavaScript array
methods.
Method 1: Using
Matter.Composite.get (Recommended)
The most direct and idiomatic way to locate an entity in Matter.js is
the Composite.get function. It searches recursively through
the specified composite (such as engine.world) for an
object matching both the provided ID and entity type.
// Syntax: Matter.Composite.get(composite, id, type)
const targetId = 5;
const body = Matter.Composite.get(engine.world, targetId, 'body');
if (body) {
console.log('Body found:', body);
} else {
console.log('No body found with ID:', targetId);
}The third argument specifies the type to retrieve
('body', 'composite', or
'constraint'). If found, the function returns the body
reference; otherwise, it returns null.
Method 2:
Using Composite.allBodies with
Array.prototype.find
Another approach is to retrieve an array of all bodies within the world and filter through them using native JavaScript. This can be useful if you already have access to the flattened body list or want to search by custom criteria in addition to the ID.
const targetId = 5;
const bodies = Matter.Composite.allBodies(engine.world);
const body = bodies.find(b => b.id === targetId);
if (body) {
console.log('Body found:', body);
}Matter.Composite.allBodies(engine.world) recursively
extracts every body in the world, including those inside nested
composites. The native .find() method returns the first
body matching the condition or undefined if no match
exists.
Setting Custom Body IDs
By default, Matter.js assigns an auto-incrementing integer to each body upon creation. If your application requires specific identifiers (such as matching DOM element IDs or database records), you can assign the ID directly in the body options:
const customBox = Matter.Bodies.rectangle(400, 200, 80, 80, {
id: 1001,
label: 'playerBody'
});
Matter.Composite.add(engine.world, customBox);
// Retrieve it later using the custom ID
const foundBox = Matter.Composite.get(engine.world, 1001, 'body');