How to Set Constraint Resting Length in Matter.js

This article explains how to define and modify the resting length of a constraint in Matter.js. By default, Matter.js calculates a constraint's resting length based on the initial distance between the connected points, but you can override this behavior by explicitly configuring the length property at initialization or altering it dynamically during runtime.

Setting the Resting Length on Creation

When instantiating a constraint using Matter.Constraint.create(), pass the length property in the options object. The value is a number representing the target resting distance in pixels.

const { Constraint } = Matter;

const constraint = Constraint.create({
    bodyA: bodyA,
    bodyB: bodyB,
    length: 150, // Resting length in pixels
    stiffness: 0.9
});

Matter.Composite.add(engine.world, constraint);

If the length property is omitted, Matter.js defaults to measuring the Euclidean distance between point A and point B at the exact moment the constraint is created.

Changing the Resting Length Dynamically

You can modify the resting length of an existing constraint at any time by directly updating its length property. This approach is useful for simulating springs, ropes, winches, or contracting muscles.

// Change the resting length dynamically
constraint.length = 75;

When updated inside an update loop or an event listener (such as beforeUpdate), the physics engine will immediately begin applying forces to adjust the bodies toward the new target distance based on the constraint's stiffness and damping settings.

Creating Pin and Pivot Joints (Zero Length)

To create a fixed pin joint or a revolute hinge where two points must stay attached together, explicitly set the length to 0.

const pin = Constraint.create({
    bodyA: bodyA,
    pointA: { x: 0, y: 0 },
    bodyB: bodyB,
    pointB: { x: 0, y: 0 },
    length: 0,
    stiffness: 1
});

A resting length of 0 paired with a high stiffness (such as 1 or close to it) forces the anchor points on both bodies to overlap completely.