How to Remove a Composite from Matter.js World
In Matter.js, managing physics simulations often requires dynamically deleting groups of bodies, constraints, or nested entities to reset states or improve performance. This guide provides the direct method for removing a Composite from the physics world using core Matter.js functions, along with options for deep removal and clearing nested objects.
Using Composite.remove()
The standard way to remove a composite from the world is using the
Matter.Composite.remove function. In Matter.js, the main
world instance is itself a composite, which acts as the
root container for all physics elements.
const { Engine, Composite } = Matter;
// Create engine and world
const engine = Engine.create();
// Create and add a composite to the world
const customComposite = Composite.create();
Composite.add(engine.world, customComposite);
// Remove the composite from the world
Composite.remove(engine.world, customComposite);Deep Removal for Nested Composites
The Composite.remove method accepts an optional third
parameter: a boolean flag named deep. When set to
true, Matter.js searches recursively through all nested
child composites to find and remove the target object:
// Remove a composite deeply nested within other composites
Composite.remove(engine.world, customComposite, true);Alternative: World.remove()
In modern versions of Matter.js, Matter.World is an
alias of Matter.Composite. You may encounter
World.remove in legacy code, which functions
identically:
Matter.World.remove(engine.world, customComposite);Clearing a Composite Without Removing It
If your objective is to retain the composite container within the
world but delete all bodies, constraints, or child composites inside it,
use Composite.clear:
// Syntax: Composite.clear(composite, keepStatic, deep)
Composite.clear(customComposite, false, true);keepStatic: When set totrue, static bodies are preserved.deep: When set totrue, nested composites are also cleared recursively.
Memory Management
Calling Composite.remove() detaches the composite from
the simulation loop and rendering system. To allow the JavaScript
garbage collector to free the associated memory, ensure you also remove
any remaining variable references to that composite in your application
code.