How to Get All Bodies in Matter.js World
This guide provides a straightforward explanation of how to access and retrieve all physics bodies currently present in a Matter.js simulation. You will learn the standard, recommended approach using built-in composite methods to find every body—including those within nested groups—as well as the direct property access method for top-level objects.
The Recommended
Method: Composite.allBodies()
The most reliable way to get an array of every body in your
simulation is using the Matter.Composite.allBodies()
method. A Matter.js World is itself a composite object that
can contain both individual bodies and other nested composites (such as
stacks, ragdolls, or compound mechanisms).
Calling Composite.allBodies() traverses the entire
hierarchy of your world and returns a flat array containing every single
body:
// Assuming 'engine' is your initialized Matter.js engine instance
const allBodies = Matter.Composite.allBodies(engine.world);
// Iterate through the bodies
allBodies.forEach((body) => {
console.log(body.id, body.position);
});The Direct Property
Method: world.bodies
If you are certain that you have not added any sub-composites and
only added direct bodies to the world using
Composite.add(engine.world, body), you can access the array
directly via the bodies property on the world object:
const directBodies = engine.world.bodies;Limitation: This array only holds bodies added
directly to the root world composite. If you create bodies inside a
Matter.Composites.stack or another custom composite and add
that composite to the world, those bodies will not
appear in engine.world.bodies. For this reason,
Matter.Composite.allBodies(engine.world) is preferred in
almost all scenarios.