Understanding the Matter.js afterRemove Event
This article provides an overview of the afterRemove
event in Matter.js, explaining its role in the physics engine lifecycle,
how it functions within composite structures, and how to implement it
for resource cleanup and state synchronization in your projects.
What is the afterRemove Event?
In Matter.js, simulation elements such as bodies, constraints, and
other composites are managed within composite containers, most notably
the root Matter.World (engine.world). The
afterRemove event is an event dispatched by a
Matter.Composite instance immediately after an object has
been completely removed from that composite.
When you call Composite.remove(world, object), Matter.js
first fires a beforeRemove event, detaches the object from
the composite's internal lists, and then fires the
afterRemove event.
Key Use Cases
The afterRemove event is typically used to manage
application state and clean up resources tied to physics objects:
- Visual Element Cleanup: Removing corresponding rendering objects (such as PixiJS sprites, Three.js meshes, or HTML DOM elements) when a physics body is deleted.
- Memory Management: Clearing references, event listeners, or custom metadata associated with the removed body to prevent memory leaks.
- Game Logic: Updating game state, such as decrementing active entity counters or awarding points when a target object is eliminated from the simulation.
How to Use afterRemove
To listen for the afterRemove event, use the
Matter.Events.on method to bind a callback function to the
target composite or world.
// Import modules
const { Engine, World, Bodies, Composite, Events } = Matter;
const engine = Engine.create();
const world = engine.world;
// Listen for the afterRemove event on the world composite
Events.on(world, 'afterRemove', (event) => {
// The removed entity is available via event.object
const removedObject = event.object;
console.log('Object successfully removed:', removedObject);
// Example: Clean up custom rendering reference
if (removedObject.renderSprite) {
removedObject.renderSprite.destroy();
}
});
// Create and add a body
const box = Bodies.rectangle(400, 200, 80, 80);
Composite.add(world, box);
// Remove the body from the world, triggering afterRemove
Composite.remove(world, box);Event Data Properties
When the callback executes, it receives an event object containing:
object: The entity that was removed (aBody,Constraint, or childComposite).source: The composite instance from which the object was removed.name: The name of the event, which is"afterRemove".
Difference Between beforeRemove and afterRemove
While beforeRemove executes while the item is still
registered within the composite, afterRemove guarantees
that the composite hierarchy has already been updated. If your cleanup
logic relies on verifying that the body is no longer present in
composite.bodies or requires the composite's bounding
limits to be recalculated, afterRemove is the appropriate
hook to use.