What Is Matter.js Engine Position Iterations?
This article provides a comprehensive overview of the
positionIterations property in Matter.js, explaining its
role in the physics simulation pipeline, how it prevents body overlap,
and how to optimize it for the best balance between simulation accuracy
and performance.
In Matter.js, the positionIterations property is a
configuration option on the Engine instance
(engine.positionIterations) that dictates how many times
per simulation update the engine resolves positional constraints and
body overlaps. When rigid bodies collide or rest against one another in
a discrete physics engine, floating-point approximations and numerical
time-stepping often cause bodies to penetrate or overlap slightly. The
position iterations phase actively pushes these overlapping bodies apart
to correct their positions.
By default, Matter.js sets positionIterations to
6. During each tick, the solver runs a relaxation loop
equal to this number:
const engine = Matter.Engine.create({
positionIterations: 6
});The Difference Between Position and Velocity Iterations
While Matter.js also features a velocityIterations
property, the two handle different aspects of the collision
response:
- Velocity iterations calculate kinetic responses, determining how forces, momentum, bounce, and friction are exchanged between bodies.
- Position iterations resolve spatial error, ensuring that bodies do not visibly sink into one another, tunnel through boundaries, or break joint constraints.
The Impact of Increasing Position Iterations
Increasing the value (e.g., to 10 or 15) increases the precision of the constraint solver:
- Reduced Sinking and Overlap: Heavy objects resting on surfaces are less likely to visually penetrate or jitter.
- Stable Stacking: High stacks of blocks or complex ragdolls stay rigid and upright rather than collapsing under compounding positional errors.
- Performance Cost: Each additional iteration multiplies the CPU workload required for collision resolution, which can lower frame rates on lower-end devices or in scenes with hundreds of active bodies.
The Impact of Decreasing Position Iterations
Decreasing the value (e.g., to 2 or 4) reduces CPU usage:
- Better Performance: Scenes run faster, making it suitable for mobile environments or simple simulations with few simultaneous collisions.
- Visual Glitches: Low values frequently lead to "spongy" behavior where bodies sink through floors, pass through thin walls, or cause joint constraints to stretch and destabilize.
When to Adjust the Property
Leave positionIterations at its default value of
6 for standard arcade games, top-down movement, or scenes
with sparse collisions. Increase the value if your simulation involves
tall stacks of physics bodies, stiff constraints, or high-speed impacts
that result in clipping. Conversely, decrease it only if profiling tools
show that constraint solving is causing bottlenecks and visual fidelity
can be compromised.