How to Remove a Body from a Matter.js World
This article explains how to properly remove a specific physics body
from a Matter.js simulation. It covers the primary API method using
Matter.Composite.remove, demonstrates how to identify and
target bodies dynamically using collision events or custom properties,
and outlines best practices to prevent memory leaks and unexpected
simulation glitches.
The Primary Method: Composite.remove
In modern versions of Matter.js, the Composite module
manages all collections of bodies, constraints, and composites. Because
engine.world is itself a composite, you remove a body by
calling Matter.Composite.remove().
// Basic syntax
Matter.Composite.remove(engine.world, targetBody);(Note: While
Matter.World.remove(engine.world, targetBody) also works,
it simply aliases Composite.remove and is considered legacy
syntax.)
Removing a Body Stored in a Variable
If you already have a direct reference to the body when creating it, you can remove it at any point in your logic:
const box = Matter.Bodies.rectangle(400, 200, 80, 80);
Matter.Composite.add(engine.world, box);
// Later, remove the specific body:
Matter.Composite.remove(engine.world, box);Removing a Body on Collision
A frequent use case is destroying a body upon impact (for example, a
projectile hitting a target). You can listen to the
collisionStart event from the Engine to detect
the pair and remove the desired body:
Matter.Events.on(engine, 'collisionStart', (event) => {
const pairs = event.pairs;
for (let i = 0; i < pairs.length; i++) {
const { bodyA, bodyB } = pairs[i];
// Check for a specific condition, such as a custom label
if (bodyA.label === 'bullet') {
Matter.Composite.remove(engine.world, bodyA);
} else if (bodyB.label === 'bullet') {
Matter.Composite.remove(engine.world, bodyB);
}
}
});Filtering and Removing by Label or ID
If you do not retain a direct reference to the body, you can search
engine.world.bodies using JavaScript's native array
methods:
// Find a body by custom label or ID
const target = engine.world.bodies.find(body => body.label === 'obstacle');
if (target) {
Matter.Composite.remove(engine.world, target);
}To remove multiple matching bodies at once:
const itemsToRemove = engine.world.bodies.filter(body => body.label === 'debris');
itemsToRemove.forEach(body => {
Matter.Composite.remove(engine.world, body);
});Best Practices
- Custom Render Loops: If you use a custom renderer
(such as PixiJS, Three.js, or HTML5 Canvas) instead of
Matter.Render, removing the body fromengine.worldonly stops physical simulation. You must separately remove the associated visual sprite or mesh from your scene. - Constraints: If the body you are removing is
attached to another body via a
Matter.Constraint, remove the constraint from the world as well to prevent runtime errors. - Garbage Collection: Ensure you clear any external array references or event listeners tied to the removed body so JavaScript's garbage collector can free the memory.