Creative Coding From Zero · Episode 12
Physics & Verlet
Physics & Verlet is Episode 12 of Creative Coding From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
Here is a secret that feels like cheating the first time you see it work: rope, chain, cloth, and wobbling jelly all come from a single trick — store the point's old position. No velocity vectors, no force accumulators, no spring equations with stiffness and damping coefficients. Just two positions per point and a rule that says "stay your rest distance apart." Run that rule a few times per frame and a flat grid of dots turns into fabric you can grab, swing, and tear in half.
This is Verlet integration, the same family of math behind the cloth in every AAA game cape and the gooey bodies in a hundred physics toys. By the end of this page you'll have written the integrate step, the distance constraint, and the relaxation loop yourself — maybe forty lines of real code — and you'll have a sheet of cloth hanging in the demo below that sways under gravity and ambient wind the instant the page loads, no input required. Grab a corner. Drag it across the screen. Turn on tearing and rip a hole through the middle. Then we'll take it apart line by line.
What you're looking at
Every white dot on screen is a particle — but a Verlet particle is a strange little thing. It has no velocity stored anywhere. It only knows where it is now and where it was last frame. The difference between those two positions is its velocity, implicitly. Move the current position and leave the old one behind, and the particle "remembers" momentum for free on the next step.
The lines between dots are constraints — sticks with a fixed rest length. Each frame we nudge the two endpoints of every stick back toward that rest length, over and over. One pass makes a loose, stretchy blob; ten passes make stiff fabric. That repeated nudging is the whole engine. Step through the six stages below and watch one point grow into a sheet you can tear.
Stage 1 — A Verlet point
The smallest possible piece: one particle, a pos, an old
position, and gravity. No springs, no constraints. It falls, hits the floor of the box,
and bounces — and the bounce is not code you wrote. It's a side effect of how
Verlet stores motion. When the floor clamps pos upward but leaves
old below, next frame's implied velocity flips. Drag the gravity slider and
watch it fall faster; the dt² scaling (more on that below) keeps the motion smooth.
Stage 2 — A stick constraint
Two particles and one stick between them. Pull them apart in your head: the constraint measures how far off the rest length they are and shoves each one half the error back. Both points fall under gravity, but the stick keeps them a fixed distance apart, so the pair swings like a tiny pendulum dangling from a pinned anchor. One stick is the atom of every rope and cloth that follows.
Stage 3 — A rope / chain
Now chain twenty particles in a line, link each to the next with a stick, and pin the top one in place. Gravity drags the tail down; the sticks pass that pull up the chain; the relaxation loop keeps the links from stretching. The result is a rope that hangs in a natural catenary curve and swings with real weight when wind pushes it. Same stick as Stage 2 — just nineteen of them in a row.
Stage 4 — A cloth grid
Lay particles out in a grid instead of a line, and connect each to its right neighbor and its bottom neighbor. That mesh of horizontal and vertical sticks is cloth. Pin the whole top row and the sheet hangs, ripples, and folds. Crank the iterations slider up and the fabric stiffens like canvas; drop it to 1 and it sags like wet silk. This is the single most important slider in the demo — feel it.
Stage 5 — Pin & tear
Same cloth, two new powers. Grab: click and drag to seize the
nearest particle and fling the sheet around. Tear: flip the tear toggle
on, and any stick stretched past a threshold simply deletes itself. Drag hard
through the fabric and it splits, frays, and drops in tatters. Tearing isn't a special
system — it's one if statement inside the constraint pass.
Stage 6 — Cloth in wind
The payoff, and the default view: a full sheet pinned along the top, breathing under gravity and a gusting ambient wind built from layered sine waves so it never stops moving. Grab a corner and swing it; turn on tearing and rip it to ribbons; regenerate for a fresh gust pattern. Everything you see is the four code blocks below, looping.
How the code works
A particle is four numbers: its current position and its previous position. We never store velocity — it lives in the gap between those two. Pinned particles carry one extra flag so we can skip them.
// One Verlet particle: where it is, and where it was.
function Point(x, y, pinned) {
return { x, y, ox: x, oy: y, pinned: !!pinned };
}
// A stick: two point indices and the rest length to hold between them.
function Stick(a, b, len) {
return { a, b, len, alive: true };
}
(a) The Verlet integrate step
This is the heart. For each free particle, compute the implied velocity as
(x − ox), scale it by a friction factor so motion
bleeds off, add gravity and wind as an acceleration times dt²,
and store the result. Then — and this order matters — save the position we
started this frame with as the new old:
function integrate(p, ax, ay, dt, friction) {
if (p.pinned) return; // pinned points never move
const vx = (p.x - p.ox) * friction; // implied velocity = pos − oldpos
const vy = (p.y - p.oy) * friction;
p.ox = p.x; // today's pos becomes tomorrow's "old"
p.oy = p.y;
p.x += vx + ax * dt * dt; // carry momentum + accel·dt² ← the dt² is key
p.y += vy + ay * dt * dt;
}
That ax * dt * dt is the part everyone gets wrong the first
time. In ordinary (Euler) integration you'd add accel * dt to velocity.
But Verlet has no velocity variable — it integrates position directly, and position
picks up acceleration as ½·a·t², so the term is dt
squared. Use a plain dt here and your gravity will be wildly
framerate-dependent and far too weak.
(b) A distance constraint
One stick. Measure the current distance between its two endpoints, find how far that is from the rest length, and push each endpoint half the error along the line connecting them. A pinned endpoint takes none of the correction so its partner takes all of it:
function solveStick(s, pts) {
const a = pts[s.a], b = pts[s.b];
let dx = b.x - a.x, dy = b.y - a.y;
const dist = Math.hypot(dx, dy) || 0.0001; // guard ÷0
const diff = (s.len - dist) / dist * 0.5; // half the error, normalized
dx *= diff; dy *= diff;
if (!a.pinned) { a.x -= dx; a.y -= dy; } // move each endpoint…
if (!b.pinned) { b.x += dx; b.y += dy; } // …toward the rest length
}
(c) The relaxation loop
A single pass over the sticks barely satisfies them — fixing stick A tugs stick B back out of place. The fix is delightfully crude: just do it again. Each full sweep over all constraints is one iteration; more iterations means stiffer, less stretchy cloth. This loop, run a handful of times per frame, is the entire solver:
// Once per frame: integrate, then relax constraints N times.
for (const p of pts) integrate(p, windX, gravity, dt, friction);
for (let k = 0; k < iterations; k++) { // ← more = stiffer fabric
for (const s of sticks) {
if (!s.alive) continue;
solveStick(s, pts);
}
constrainToBox(pts); // keep points inside the canvas each pass
}
(d) Mouse grab + tear
Grabbing is just overwriting a particle's position with the mouse each frame — the
Verlet step then drags the rest of the sheet along by the constraints. Tearing lives
inside the constraint solve: if a stick is stretched past a multiple of its rest length,
flip its alive flag off and stop solving it. The hole appears instantly:
// grab: pin the nearest point to the cursor while dragging
if (mouse.down && grabbed) {
grabbed.x = mouse.x; grabbed.y = mouse.y;
grabbed.ox = mouse.x; grabbed.oy = mouse.y; // zero its velocity so it doesn't fling
}
// tear: inside the constraint loop, before solving the stick
if (tearOn) {
const d = Math.hypot(b.x - a.x, b.y - a.y);
if (d > s.len * TEAR_RATIO) { s.alive = false; continue; }
}
That's the complete engine: a struct with two positions, an integrate step with a
dt², a half-the-error distance constraint, a loop that runs it N times, and
two mouse hooks. Everything in the demo — rope, chain, grid, tear — is those parts
arranged differently.
Common pitfalls
- Too few constraint iterations = stretchy cloth. One pass leaves the sheet rubbery and saggy; that's not a bug, it's the stiffness dial. Real cloth wants 5–15 passes. More passes cost CPU, so it's a direct quality/perf trade — feel it on the iterations slider.
- Explosions. If the simulation suddenly flings particles to
infinity, you've over-stretched a constraint, used too few iterations, or let a single
frame's
dtspike (tab-switch, slow frame). Defenses: clamp the per-framedtto a sane max, clamp implied velocity, keep at least a few iterations, and make sure some points are pinned so the structure has an anchor. - The
dt²trap. Verlet integrates position, so acceleration enters asaccel * dt * dt, not Euler'saccel * dt. Forget the square and gravity becomes far too weak and framerate-dependent. This is the single most common Verlet mistake. - Tearing needs a threshold, not a force. Don't try to compute
stress. Just measure the stick's current length; if it exceeds, say,
4×its rest length, delete it. Setting the threshold too low makes cloth that disintegrates on its own; too high and it never tears. - Pinned points must skip integration. If you let a pinned anchor run through the integrate step, it'll drift and the whole sheet will sink. Pinned points are skipped in both the integrate step and the constraint nudge — they are immovable on purpose.
- Solving order bias. Because constraints are solved one after another in array order, the last one solved "wins" slightly. It's usually invisible, but if your cloth leans one way, that's why — more iterations average it out.
Exercises
- A flag in wind. Take the cloth grid but pin only the left column instead of the top row, and push it with a stronger, gustier horizontal wind. You've built a flag. Try adding a faint diagonal constraint on each cell to stop it shearing into a parallelogram.
- A hanging bridge. Build a horizontal rope (Stage 3) but pin both ends, then hang short vertical "plank" sticks off each particle. Drop a heavy free particle onto it and watch the bridge sag and recover. Bump the iterations so the deck doesn't stretch under load.
- Pour soft-body blobs. Make a small ring of particles all linked to each other and to a center point, so it holds a round shape but squishes on impact. Spawn a few on a timer at the top and let them rain into the box, jiggling and piling up. That center-spoke layout is the cheapest soft body there is.
What's next
Episode 13 — Tiling & Truchet patterns. We leave physics behind and go fully graphic: a grid of tiles, each holding one of a few simple motifs (quarter-circle arcs, diagonals), placed by a seeded coin-flip — and out of that nothing-special rule emerges endless flowing mazes and woven knots. It's the most pattern-per-line technique in the whole series.
Want to push this episode further first? Move the solver onto the GPU in the
shaders series, or take these particles into 3D
with the three.js series — a Verlet cloth in 3D
is the exact same code with a z added.