Understanding Matter.Engine.clear in Matter.js

Matter.Engine.clear is a core utility method in Matter.js designed to reset an engine's internal simulation state without requiring developers to instantiate a new Engine object. This article examines the exact mechanics behind how this method flushes active collision pairs, purges broadphase and narrowphase structures, clears the composite world tree, and severs dangling object references to prevent memory leaks during scene transitions or simulation restarts.

Clearing the World Composite

The clearance process begins at the root container of the simulation: engine.world. Under the hood, Matter.Engine.clear invokes Matter.Composite.clear(engine.world, false).

This operation recursively traverses the composite hierarchy:

By passing false as the second argument, the root composite itself is preserved while its contents are completely evacuated.

Flushing Collision Pairs

During execution, Matter.js tracks persistent contact points across frames using a dedicated collision pair manager located at engine.pairs. This cache stores active collision pairs (Pair objects), separation vectors, friction data, and penetration depths to solve impulses efficiently over time.

Matter.Engine.clear calls Matter.Pairs.clear(engine.pairs). This operation:

  1. Empties the pairs.table hash map, which indexes collisions using unique body pair keys (e.g., idA_idB).
  2. Clears the pairs.list array, which holds active contact manifolds scheduled for resolution.
  3. Resets internal collision metrics, including active collision counts and collision lifecycle states (collisionStart, collisionActive, collisionEnd).

Purging the pairs table ensures that newly spawned bodies in subsequent frames do not inherit outdated impulse values or phantom collision responses from previous objects.

Resetting Broadphase Spatial Structures

Before calculating detailed vertex-level intersections, Matter.js uses a broadphase collision detector (such as a spatial grid or bounding box tree) to filter out distant bodies.

Matter.Engine.clear resets this system by:

This prevents the narrowphase collision solver from receiving stale body pairs that no longer exist in the physics world.

Resetting Engine Timing and Metrics

The engine's internal step pipeline relies on frame delta accumulation to maintain deterministic updates. When cleared:

Facilitating Garbage Collection

JavaScript utilizes reference-counting and mark-and-sweep garbage collection. By systematically emptying arrays (bodies, constraints, composites, pairs.list) and setting hash table entries (pairs.table) to empty structures, Matter.Engine.clear breaks circular references between collision pairs and body definitions.

Once these references are severed from the root engine instance, the JavaScript runtime's garbage collector can safely reclaim the memory allocated for body vertices, collision caches, parts arrays, and render bindings.