Matter.Composite.rebase in Matter.js Explained
In Matter.js, managing complex multi-body assemblies often involves
nesting bodies, constraints, and sub-composites within hierarchical
structures. This article explains the role of
Matter.Composite.rebase, detailing how it recursively
updates ownership hierarchies, repairs internal parent-child
relationships after structural modifications, and ensures the physics
engine processes composite trees reliably.
A Matter.Composite is a container that holds collections
of bodies, constraints, and other nested composites. In complex
simulations, elements are frequently moved, detached, or transferred
from one composite container to another. When these manipulations occur,
the internal references linking an element to its owning composite can
become decoupled, stale, or point to an outdated parent.
Matter.Composite.rebase(composite) solves this issue by
traversing the entire tree structure rooted at the specified composite
and updating all internal parent pointers. When invoked, it inspects
every child body, constraint, and sub-composite in the tree, setting
their respective .parent properties to reflect their actual
position within the current hierarchy.
This re-indexing process is essential for several reasons:
- Hierarchy Integrity: It guarantees that every nested component correctly identifies the composite that directly owns it.
- Event and State Propagation: Matter.js relies on parent-child references to propagate state changes, handle removals, and apply structural updates upward and downward through the composite tree.
- Accurate Removal and Cleanup: If a body or
constraint still points to an old parent, operations such as
Composite.removecan fail silently or attempt to remove the item from a container it no longer resides in, leading to orphaned objects or memory leaks.
You should use Matter.Composite.rebase whenever you
manually restructure your composite hierarchy, such as reparenting a
sub-composite, merging two distinct composite structures, or shifting a
group of bodies between different layers of a compound object. Calling
rebase immediately after these reorganizations synchronizes
the structural graph, ensuring that subsequent physics steps and
hierarchy queries remain consistent.