Matter.Composite.allComposites in Matter.js

This article explains how the Matter.Composite.allComposites method operates within the Matter.js 2D physics engine to provide comprehensive visibility into nested composite hierarchies. By recursively traversing complex parent-child tree structures, this function flattens hierarchical groupings into an accessible collection, enabling developers to monitor, inspect, and manipulate modular assemblies across an entire physics simulation without manual tree-traversal logic.

Understanding Composite Hierarchies in Matter.js

In Matter.js, a Composite acts as an organizational container that can hold rigid bodies, constraints, and other nested composites. Complex simulation elements—such as ragdolls, multi-part vehicles, or procedurally generated structures—are typically built as self-contained sub-composites and then added to the top-level engine.world.

While this hierarchical design promotes modular architecture and clean encapsulation, it introduces deep nesting. Accessing a specific sub-assembly buried multiple layers deep using standard properties (such as composite.composites) requires custom recursive algorithms to walk the tree.

How Matter.Composite.allComposites Works

The Matter.Composite.allComposites(composite) function solves the visibility problem by executing an automated, depth-first search across the specified root composite.

When passed a parent composite (most commonly engine.world), the function:

  1. Traverses the Tree: It evaluates the target composite and identifies all child composites residing directly inside it.
  2. Recurses Child Branches: For each discovered child, it recursively checks for further nested composites, repeating the process until the leaf nodes of the architecture are reached.
  3. Flattens the Results: It collates references to every visited composite into a single, one-dimensional array.

The resulting flat array includes every composite in the structure, regardless of its depth level in the hierarchy.

Practical Implications for Architecture Visibility

Using Matter.Composite.allComposites provides several operational advantages for managing nested simulation groups:

By abstracting away tree traversal, Matter.Composite.allComposites ensures that modular, deeply nested architectures remain transparent, queryable, and maintainable throughout the simulation lifecycle.