Matter.js Constraint Stiffness Explained
In Matter.js, constraints are used to link two physics bodies or fix
a single body to a specific point in the simulation world. This article
explains the role of the stiffness property on a
constraint, detailing how its numerical values govern physical behavior
ranging from loose, elastic springs to rigid, unyielding rods, and how
it interacts with the physics engine solver.
What Stiffness Controls
The stiffness property defines the rigidity or
elasticity of a constraint. When two bodies connected by a constraint
move relative to each other, the engine calculates a restorative force
to pull them back to the constraint's specified length. The
stiffness property dictates how strongly and quickly that
restorative force is applied.
In mechanical terms, setting stiffness is equivalent to
setting the spring constant (\(k\)) in
Hooke's Law:
- High stiffness creates a stiff, rigid connection that resists deformation.
- Low stiffness creates a soft, spring-like connection that stretches or compresses easily under tension or load.
The Stiffness Value Range
The stiffness property accepts a floating-point number,
typically ranging from 0 to 1:
1.0(Maximum Rigidity): The constraint acts like a solid bar or rod. It attempts to eliminate all displacement instantly within each simulation step, preventing stretching or compressing.0.1to0.9(Spring/Elastic): The constraint behaves like an elastic band or mechanical spring. Lower values allow the bodies to separate further from the resting length under external forces before pulling them back.0.0(No Force): The constraint exerts no restorative force, effectively disabling the physical link while keeping the object reference active.
Pairing Stiffness with Damping
When using lower stiffness values to simulate springs, bodies will
naturally oscillate back and forth around the resting length. To prevent
endless bouncing or instability, stiffness is commonly
configured alongside the damping property:
dampingcontrols how quickly oscillations lose energy. A value around0.1prevents infinite bounce, creating a realistic suspension or shock-absorber effect.
Solver Iterations and Perceived Rigidity
Even when stiffness is set to 1.0, chains
of constraints or heavy masses may still show slight stretching. This
happens because Matter.js solves constraints iteratively. To achieve
true rigidity in complex setups, you may need to increase
engine.constraintIterations in your engine configuration
alongside setting stiffness: 1.