13

I love verlet integration for cheap 2D physics, but every quick AI version I got would look great for two seconds and then the cloth would violently explode as constraints fought each other.

The naive prompt didn't mention constraint iterations or clamping, so a single dt spike sent everything to infinity. The fix was to spell out the exact Verlet loop: substep count, constraint relaxation iterations, a max-correction clamp, and a clamped timestep. Stable rope, stable cloth, draggable and pinnable.

Sharing the prompt. It's model-agnostic but I ran it on Gemini.

THE PROMPT
Implement a 2D Verlet integration physics sandbox in a single HTML canvas file, vanilla JS, 60fps. Support a hanging rope and a cloth sheet, both draggable with the mouse.

Simulation (follow precisely for stability):
1. Points store {x, y, oldx, oldy}. Verlet step: vx = (x-oldx)*damping; oldx = x; x += vx + ax*dt*dt (damping 0.99, gravity 1200px/s^2).
2. Distance constraints between linked points: after integration, run 5 relaxation iterations that move each pair back toward its rest length (split correction 50/50 unless a point is pinned).
3. Clamp per-iteration correction to at most 20% of rest length so one bad frame can't launch a point to infinity.
4. Clamp dt: if a frame is longer than 1/30s, cap it (avoids the tab-switch explosion). Use a fixed sub-step of 1/120s, running as many substeps as fit in the frame.
5. Pinned points (top row of cloth, top of rope) ignore integration.

Interaction: click-drag to grab the nearest point; hold to pin/unpin; a 'tear' mode that removes constraints stretched past 3x rest length. Render points as thin lines between links, cloth as a wireframe. Add a wind toggle (sine gust on x). Show FPS. Explain in a comment why the correction clamp and dt clamp keep it stable. Do NOT skip the iteration count or the clamps.

1 Answer

5

The dt clamp is the fix nobody remembers until their cloth explodes on a tab switch, thank you for putting it front and center. For the tear mode, I'd also have it fade the torn segment's neighbors slightly so a rip reads visually. And if you want the cloth to settle faster without more iterations, run the constraint passes in alternating order (front-to-back, then back-to-front) each frame, it distributes the error more evenly than always relaxing in the same direction.

THE PROMPT
Alternate constraint solve direction each frame: on even frames iterate constraints 0..n, on odd frames iterate n..0. Reduces directional bias and settles the cloth faster at the same iteration count.

Your Answer