How to Access Constraints in a Matter.js World
In Matter.js, constraints are used to create joints, springs, and connections between rigid bodies or between a body and a fixed world point. This guide explains how to retrieve, inspect, and manipulate the constraints currently active within your Matter.js physics engine, covering both the built-in composite utility methods and direct object property access.
Using
Composite.allConstraints
The most reliable way to access constraints in Matter.js is using the
Matter.Composite.allConstraints method. Because a
World is fundamentally a Composite that can
contain nested composites, querying the world using this helper ensures
you retrieve all constraints, including those nested within child
composites (such as complex assemblies or ragdolls).
// Access all constraints in the physics world
const constraints = Matter.Composite.allConstraints(engine.world);
console.log(constraints);This returns a flat array of all Constraint objects
active in the simulation.
Direct Access via
engine.world.constraints
If your simulation only uses top-level constraints and does not nest
them within sub-composites, you can access the array directly through
the constraints property of the engine.world
object:
// Access top-level constraints directly
const topLevelConstraints = engine.world.constraints;
console.log(topLevelConstraints);Note: This property only contains constraints added directly to
engine.world. Any constraints added to nested composites
will not appear in this array.
Inspecting and Modifying Accessed Constraints
Once you have the array of constraints, you can iterate through them to inspect their properties or modify their behavior in real time:
const constraints = Matter.Composite.allConstraints(engine.world);
constraints.forEach((constraint) => {
// Inspect connected bodies
console.log('Body A:', constraint.bodyA);
console.log('Body B:', constraint.bodyB);
// Read or alter physical properties
console.log('Current stiffness:', constraint.stiffness);
constraint.stiffness = 0.5; // Update stiffness dynamically
});Finding a Specific Constraint
To find a specific constraint, assign a custom label or
id when creating it, then search the array:
// Definition
const rope = Matter.Constraint.create({
bodyA: bodyA,
bodyB: bodyB,
label: 'mainRope'
});
Matter.Composite.add(engine.world, rope);
// Retrieval
const allConstraints = Matter.Composite.allConstraints(engine.world);
const targetConstraint = allConstraints.find(c => c.label === 'mainRope');