TExcelTAD
Home › Game Physics & Animation › Distance Constraints

Distance Constraints

A constraint is a rule the simulation must keep true: "these two points stay 0.2 m apart", "this door rotates only around its hinge", "this box doesn't go into the floor". Contacts from the previous section are constraints too, ones that can only push. This lesson uses the simplest one, a distance constraint, to show the two families of constraint solvers games use, and builds the foundation for ropes, cloth and soft bodies.

Writing a constraint as a function

Every constraint is a function C of the positions that is zero when the rule holds:

C(p1, p2) = |p2 - p1| - L

C > 0 means the link is stretched, C < 0 compressed. The gradient of C tells you which way to move each point to change C fastest. For a distance constraint it is just the unit direction n = (p2 - p1) / |p2 - p1| (for p2) and -n (for p1).

Rigid-body engines solve constraints at the velocity level with impulses, like contacts: the time derivative of C must become zero. Position Based Dynamics (PBD), used for cloth, ropes and soft bodies (and by Unreal's Chaos cloth, NVIDIA Flex, Obi and many custom solvers), works directly on positions, which is simpler and very stable.

Position Based Dynamics in one formula

Each step, PBD does:

  1. Predict positions from velocities: v += g · dt, p = x + v · dt.

  2. For a few iterations, project each constraint: move the points the smallest amount that makes C = 0, split by inverse mass w = 1/m:

    Δp1 = +w1 / (w1 + w2) · C · n
    Δp2 = -w2 / (w1 + w2) · C · n
  3. Derive velocities from the movement: v = (p - x) / dt, then x = p.

Step 3 is what makes PBD unconditionally stable: velocities can never be larger than what the positions actually did, so there is no stiff spring to explode (compare with Springs and Damping).

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>

struct Vec2 { double x, y; };
double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }

// Project one distance constraint (rest length L) on two points with inverse masses w1, w2.
void project(Vec2& p1, Vec2& p2, double w1, double w2, double L) {
    Vec2 d{p2.x - p1.x, p2.y - p1.y};
    double len = std::sqrt(d.x * d.x + d.y * d.y);
    double C = len - L;
    Vec2 n{d.x / len, d.y / len};
    double s = C / (w1 + w2);
    p1.x += w1 * s * n.x; p1.y += w1 * s * n.y;
    p2.x -= w2 * s * n.x; p2.y -= w2 * s * n.y;
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    struct Case { const char* name; double w1, w2; };
    for (Case c : {Case{"equal masses", 1, 1}, Case{"p1 4x heavier", 0.25, 1}, Case{"p1 pinned", 0, 1}}) {
        Vec2 p1{0, 0}, p2{3, 4};                                    // 5 m apart, rest length 2 m
        project(p1, p2, c.w1, c.w2, 2.0);
        double len = std::hypot(p2.x - p1.x, p2.y - p1.y);
        std::cout << std::left << std::setw(13) << c.name << std::right << ": p1 = (" << z0(p1.x) << ", " << z0(p1.y) << "), p2 = (" << p2.x << ", " << p2.y << "), length " << len << "\n";
    }
}
equal masses : p1 = (0.900, 1.200), p2 = (2.100, 2.800), length 2.000
p1 4x heavier: p1 = (0.360, 0.480), p2 = (1.560, 2.080), length 2.000
p1 pinned    : p1 = (0.000, 0.000), p2 = (1.200, 1.600), length 2.000

One projection fixes one constraint exactly, the lighter point moves more, and a pinned point (w = 0) doesn't move at all, which is how you attach a rope to the world. Momentum is conserved because both corrections are equal and opposite once multiplied by mass.

Many constraints: iterations and mass ratios

A chain has many constraints that share points. Fixing one link breaks its neighbours a little, so PBD loops over all constraints several times per step, the same Gauss-Seidel idea as sequential impulses. With too few iterations, the error can't travel along the chain within one step, and the chain stretches under gravity. A heavy weight at the end makes it far worse:

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>
#include <vector>

struct Vec2 { double x, y; };

// A chain of 10 links (0.2 m each) hanging from a pinned particle. Returns the total stretch after 2 s.
// mode 0: PBD with a stiffness factor; mode 1: XPBD with compliance alpha.
double hang(int iterations, int mode, double stiffness, double alpha, double endMass = 1) {
    const int n = 11; const double L = 0.2, dt = 1.0 / 60, g = 9.81;
    std::vector<Vec2> x(n), v(n, {0, 0});
    std::vector<double> w(n, 1.0);
    for (int i = 0; i < n; i++) x[i] = {0, -L * i};
    w[0] = 0;                                   // pinned
    w[n - 1] = 1 / endMass;
    double sum = 0;
    for (int step = 0; step < 120; step++) {
        std::vector<Vec2> p(n);
        for (int i = 0; i < n; i++) {
            if (w[i] > 0) v[i].y -= g * dt;
            p[i] = {x[i].x + v[i].x * dt, x[i].y + v[i].y * dt};
        }
        std::vector<double> lambda(n - 1, 0.0);
        for (int it = 0; it < iterations; it++) {
            for (int i = 0; i + 1 < n; i++) {
                Vec2 d{p[i + 1].x - p[i].x, p[i + 1].y - p[i].y};
                double len = std::sqrt(d.x * d.x + d.y * d.y);
                Vec2 nrm{d.x / len, d.y / len};
                double C = len - L;
                double wsum = w[i] + w[i + 1];
                double dl;
                if (mode == 0) dl = -stiffness * C / wsum;
                else { double at = alpha / (dt * dt); dl = (-C - at * lambda[i]) / (wsum + at); lambda[i] += dl; }
                p[i].x -= w[i] * dl * nrm.x; p[i].y -= w[i] * dl * nrm.y;
                p[i + 1].x += w[i + 1] * dl * nrm.x; p[i + 1].y += w[i + 1] * dl * nrm.y;
            }
        }
        for (int i = 0; i < n; i++) { v[i] = {(p[i].x - x[i].x) / dt, (p[i].y - x[i].y) / dt}; x[i] = p[i]; }
        if (step >= 60) sum += -x[n - 1].y - L * (n - 1);    // average over the second second
    }
    return sum / 60;
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    std::cout << "PBD, stiffness 1  | average stretch of a 2 m chain\n";
    std::cout << "iterations        | 1 kg end | 100 kg end\n";
    for (int it : {1, 2, 5, 10, 20, 50})
        std::cout << std::setw(10) << it << "        | " << std::setw(6) << hang(it, 0, 1.0, 0) << " m | " << std::setw(6) << hang(it, 0, 1.0, 0, 100) << " m\n";
}
PBD, stiffness 1  | average stretch of a 2 m chain
iterations        | 1 kg end | 100 kg end
         1        |  0.123 m |  4.574 m
         2        |  0.061 m |  1.686 m
         5        |  0.023 m |  0.367 m
        10        |  0.011 m |  0.255 m
        20        |  0.005 m |  0.134 m
        50        |  0.001 m |  0.050 m

With equal masses, 5–10 iterations keep a 2 m chain within 1–2 cm of its length. With a 100 kg weight on 1 kg links, even 20 iterations leave it 13 cm too long, and one iteration lets it stretch to more than three times its length. Each projection splits the error by inverse mass, so the heavy end barely moves and the light links absorb all the correction, and the error crawls up the chain one link per iteration. This is the same reason rigid-body engines struggle with large mass ratios: a heavy wrecking ball on a light chain, a car resting on a light crate. Fixes, in order of preference: make the masses closer, add more iterations or substeps, or solve the chain in a different order (from the heavy end, or with a direct solver for the whole chain).

Stiffness that doesn't depend on iterations: XPBD

Plain PBD makes constraints soft by multiplying the correction by a stiffness factor k < 1. The trouble: the effective stiffness then depends on the iteration count and time step, so a cloth tuned at 10 iterations becomes stiffer at 20. XPBD (extended PBD) fixes this by giving each constraint a compliance α (inverse stiffness, in m/N) and a Lagrange multiplier λ that accumulates over the iterations:

α̃  = α / dt²
Δλ = (-C - α̃ · λ) / (w1 + w2 + α̃)
λ += Δλ,   Δp1 = -w1 · Δλ · n,   Δp2 = +w2 · Δλ · n

With α = 0 it is exactly PBD with full stiffness. With α > 0 the constraint behaves like a real spring of stiffness 1/α, independent of the number of iterations:

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>
#include <vector>

struct Vec2 { double x, y; };

// A chain of 10 links (0.2 m each) hanging from a pinned particle. Returns the total stretch after 2 s.
// mode 0: PBD with a stiffness factor; mode 1: XPBD with compliance alpha.
double hang(int iterations, int mode, double stiffness, double alpha, double endMass = 1) {
    const int n = 11; const double L = 0.2, dt = 1.0 / 60, g = 9.81;
    std::vector<Vec2> x(n), v(n, {0, 0});
    std::vector<double> w(n, 1.0);
    for (int i = 0; i < n; i++) x[i] = {0, -L * i};
    w[0] = 0;                                   // pinned
    w[n - 1] = 1 / endMass;
    double sum = 0;
    for (int step = 0; step < 120; step++) {
        std::vector<Vec2> p(n);
        for (int i = 0; i < n; i++) {
            if (w[i] > 0) v[i].y -= g * dt;
            p[i] = {x[i].x + v[i].x * dt, x[i].y + v[i].y * dt};
        }
        std::vector<double> lambda(n - 1, 0.0);
        for (int it = 0; it < iterations; it++) {
            for (int i = 0; i + 1 < n; i++) {
                Vec2 d{p[i + 1].x - p[i].x, p[i + 1].y - p[i].y};
                double len = std::sqrt(d.x * d.x + d.y * d.y);
                Vec2 nrm{d.x / len, d.y / len};
                double C = len - L;
                double wsum = w[i] + w[i + 1];
                double dl;
                if (mode == 0) dl = -stiffness * C / wsum;
                else { double at = alpha / (dt * dt); dl = (-C - at * lambda[i]) / (wsum + at); lambda[i] += dl; }
                p[i].x -= w[i] * dl * nrm.x; p[i].y -= w[i] * dl * nrm.y;
                p[i + 1].x += w[i + 1] * dl * nrm.x; p[i + 1].y += w[i + 1] * dl * nrm.y;
            }
        }
        for (int i = 0; i < n; i++) { v[i] = {(p[i].x - x[i].x) / dt, (p[i].y - x[i].y) / dt}; x[i] = p[i]; }
        if (step >= 60) sum += -x[n - 1].y - L * (n - 1);    // average over the second second
    }
    return sum / 60;
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    std::cout << "iterations | PBD k = 0.5 | XPBD alpha = 1e-4 | XPBD alpha = 1e-3\n";
    for (int it : {1, 2, 5, 10, 20, 50})
        std::cout << std::setw(10) << it << " | " << std::setw(8) << hang(it, 0, 0.5, 0) << " m | " << std::setw(15) << hang(it, 1, 0, 1e-4)
                  << " m | " << std::setw(15) << hang(it, 1, 0, 1e-3) << " m\n";
}
iterations | PBD k = 0.5 | XPBD alpha = 1e-4 | XPBD alpha = 1e-3
         1 |    0.397 m |           0.191 m |           0.441 m
         2 |    0.209 m |           0.099 m |           0.440 m
         5 |    0.078 m |           0.065 m |           0.442 m
        10 |    0.038 m |           0.056 m |           0.442 m
        20 |    0.018 m |           0.055 m |           0.442 m
        50 |    0.007 m |           0.055 m |           0.442 m

The PBD column keeps changing with the iteration count, so the "material" of the chain changes whenever the solver settings change. Both XPBD columns converge to a fixed stretch (5.5 cm and 44 cm) that depends only on the compliance. That is why XPBD is popular in modern cloth and soft-body solvers, and why Jolt's soft bodies, for example, are tuned with a compliance per constraint rather than an iteration-dependent stiffness. Many XPBD solvers also replace iterations with substeps (several small steps with one iteration each), which converges faster for the same cost.

Note: Distance constraints only pull points apart or together along the line between them. Add bending constraints (between every second point) to make a rope or cloth resist folding, and collision constraints (an inequality: C ≥ 0, only projected when violated) to keep it out of the world.

Test yourself

In a PBD distance constraint, how is the correction split between the two points?

  1. Equally
  2. In proportion to inverse mass, so the lighter point moves more
  3. Only the second point moves
  4. In proportion to mass, so the heavier point moves more

Why does a heavy weight on a light PBD chain stretch the chain so much?

  1. Gravity is stronger on heavy objects
  2. The light links absorb almost all of each correction, so the error travels up the chain slowly
  3. PBD ignores mass
  4. Heavy objects have no constraints

What problem does XPBD's compliance solve compared with PBD's stiffness factor?

  1. It removes the need for gravity
  2. Effective stiffness no longer depends on the iteration count and time step
  3. It makes the solver run on the GPU
  4. It handles collisions automatically