How to Clear All Bodies from a Matter.js World
Clearing all bodies from a Matter.js simulation is a common requirement when resetting game levels, restarting scenes, or managing memory in physics-based web applications. This guide explains the most efficient, built-in methods to remove all physics bodies from a Matter.js world instance, details the difference between keeping or discarding static boundaries, and covers how to ensure proper garbage collection without breaking the physics engine loop.
Using
Composite.clear (Recommended)
In modern versions of Matter.js, Matter.World is an
alias for Matter.Composite. The cleanest and most
performant way to clear bodies is by calling the
Composite.clear method on your engine's world instance.
// Remove all bodies, constraints, and nested composites
Matter.Composite.clear(engine.world, false);Method Parameters
The Matter.Composite.clear method accepts the following
arguments:
composite(Composite): The composite instance to clear, typicallyengine.world.keepStatic(Boolean): Determines whether static bodies (such as ground, walls, and static platforms) should remain in the world.- Pass
falseto delete everything, including static boundaries. - Pass
trueto remove only dynamic bodies while keeping your static scene layout intact.
- Pass
deep(Boolean, optional): Defaults tofalse. If set totrue, it recursively clears all child composites contained within the specified composite.
Preserving Static Boundaries Example
If you want to clear floating debris, player characters, or dynamic
objects while keeping room boundaries, set keepStatic to
true:
// Remove dynamic bodies while keeping static walls and floors
Matter.Composite.clear(engine.world, true);Alternative: Using
Composite.remove
If you need fine-grained control or want to selectively delete all
currently registered bodies without resetting other elements like
standalone constraints, you can query all bodies using
Composite.allBodies and pass the array directly to
Composite.remove:
const allBodies = Matter.Composite.allBodies(engine.world);
// Remove the retrieved array of bodies from the world
Matter.Composite.remove(engine.world, allBodies);Cleaning Up Renderer Caches
If you are using the built-in Matter.Render module,
removing bodies from the physics engine automatically stops them from
rendering in the next frame. However, if you maintain custom references,
sprite objects, or an external rendering pipeline (such as PixiJS or
Three.js), ensure you also release those references or remove
corresponding graphics containers to prevent visual artifacts and memory
leaks:
// 1. Clear the physics world
Matter.Composite.clear(engine.world, false);
// 2. Clear custom tracking arrays if applicable
myCustomSpriteArray.forEach(sprite => sprite.destroy());
myCustomSpriteArray = [];