What Is the beforeAdd Event in Matter.js?

This article provides an overview of the beforeAdd event in the Matter.js 2D physics engine, explaining its core function, when it is triggered, and how developers can utilize it. You will learn how this lifecycle event operates within the Matter.js Composite module, explore practical use cases such as object validation and dynamic modification, and see a practical implementation example.

Understanding the beforeAdd Event

In Matter.js, the simulation hierarchy is managed through composites. A Composite is a container that can hold physics bodies, constraints, and even other nested composites (such as the default root container, engine.world).

The beforeAdd event is fired by a composite immediately before one or more items (bodies, constraints, or child composites) are officially appended to it. Because it triggers prior to the insertion being finalized, it gives developers a hook into the entity creation lifecycle.

How beforeAdd Works

When you call Composite.add(composite, object), Matter.js executes the addition process through the following internal sequence:

  1. Triggers the beforeAdd event on the target composite.
  2. Appends the given object or array of objects to the composite's internal collections.
  3. Triggers the afterAdd event to signal completion.

The callback function listening to beforeAdd receives an event object containing data about the incoming elements. The most notable property is event.object, which references the body, constraint, or composite currently being introduced.

Common Use Cases

The beforeAdd event is best suited for pre-processing tasks:

Implementation Example

To listen for the beforeAdd event, use the Matter.Events.on method targeting your chosen composite (often engine.world):

const { Engine, Composite, Bodies, Events } = Matter;

const engine = Engine.create();

// Listen for the beforeAdd event on the world composite
Events.on(engine.world, 'beforeAdd', (event) => {
    console.log('An object is about to be added:', event.object);

    // Example: Dynamically adjust friction before the body enters the simulation
    if (event.object.type === 'body') {
        event.object.friction = 0.05;
    }
});

// Adding a body triggers the beforeAdd event
const box = Bodies.rectangle(400, 200, 80, 80);
Composite.add(engine.world, box);

beforeAdd vs. afterAdd

While beforeAdd runs prior to the state update, afterAdd fires once the addition is finalized. If you need to manipulate an entity's initial properties without causing race conditions or intermediate physics recalculations, beforeAdd is the appropriate hook. If you need to perform actions that depend on the entity already being accessible within the composite hierarchy, use afterAdd.