Who draws the way things fall?
You've seen it in video games: a stack of crates topples, a character swings on a rope, a bridge sags under a truck. Nobody draws those movements frame by frame. A computer solves Newton's laws of motion thousands of times a second to work out where everything goes next. The program that does this is called a physics engine.
This simulation is a physics-engine sandbox. There's a rope hanging from the ceiling, a loose chain, a bridge across a gap, and a row of beads joined by springs, and you can grab any of them with a finger or the mouse and swing them about. While you play, let's ask a few questions. How does a computer make something that behaves like a rope? Where is it like a real rope, and where isn't it? These questions have a long back story, from a 17th-century race to find the shape of a hanging chain to an 18th-century mechanics book that proudly contained no pictures at all.
A rope is sticks and pins
A physics engine's job is surprisingly humble. It chops time into short steps, each 1/120 of a second long in this simulation, and for every object it works out "from the velocity now and the forces acting now, what are the velocity and position a moment later?", over and over again. Each object is a rigid body that never bends, described only by its position, orientation, velocity and angular velocity. It is a bit like drawing a flip book one page at a time, except that the artist is the equation of motion, and each new page depends only on the positions, velocities and forces on the page before.
So how do you make a rope? You line up lots of short sticks and pin their ends together. Each pin is a revolute joint: a promise, called a constraint, that a certain point on one body always sits on top of a certain point on the next, so the only thing they can do is turn about that point. The rope here has 24 sticks, each just m long, so the whole thing looks like a flexible cord. The chain is 14 boxes pinned the same way, and the bridge is 16 planks.
When you grab something, the engine uses a mouse joint. It ties the point under your finger to the object with an invisible spring and damper and pulls. That's why objects don't stick rigidly to your finger: they follow a little behind, building up speed.
Equations of motion draw the next frame
What the engine solves, in the end, is Newton's equation of motion. For a rigid body of mass and moment of inertia , acted on by a force and a torque ,
The engine approximates this over a time step . Planck.js, like Box2D, first updates the velocity and then uses the new velocity to update the position:
Stepping a motion forward bit by bit goes back to a method Leonhard Euler described in his book on integral calculus of 1768–1770.
Is that right? Let's check. In this simulation's tests, an object dropped for s reaches m/s in the engine too, exactly as it should. But the distance fallen comes out about cm more than the true m. Where does the difference come from? After steps the speed is . Since each position update uses the new speed, the distance fallen in steps is
so the method runs ahead of the true value by : about 2 cm for s and s. Smaller steps make the error smaller.
Why the velocity goes first
Why bother updating the velocity first? Try the obvious alternative, advancing both position and velocity from the old values, on a spring, where the acceleration is . One step is
Work out , which is proportional to the energy: the cross terms cancel exactly, leaving . The energy is multiplied by at every step. The swing slowly grows until the simulation blows up. A playground swing computed this way would pump itself higher and higher with nobody pushing. With the velocity-first method, the energy only wobbles slightly around its true value and never runs away. The engine prefers "never explodes" to "exactly right."
Why do the joints drift a little?
Joints are enforced not with ordinary forces but with impulses. When two pinned points start to drift apart, the engine computes an impulse that cancels the drift and applies it to both bodies. With many joints in a row, fixing one disturbs its neighbor, so the engine sweeps over all of them several times, getting closer each time. This is called an iterative solver. It is like fixing a wobbly table: wedge paper under one leg and another leg lifts; go round the legs a few times and it more or less settles. The engine, however, stops after a fixed number of rounds and moves on to the next step. It never gets them exactly right, so a hard pull makes the joints separate slightly. The panel shows the largest separation of any pin, in millimeters.
Mechanics with "promises" like joints took a big step forward in Joseph-Louis Lagrange's Analytical Mechanics of 1788, which used multipliers to calculate the forces needed to keep the constraints, the constraint forces. Its preface proudly announces that no figures will be found in the work, about as far as you can get from a sandbox where you can see everything.
The pendulum at the end of the rope
The weight on the end of the rope is also a pendulum. When a bob on a string of length swings out by an angle , the component of gravity along the circle, , pulls it back. For small swings , and with the arc length this gives : the same simple harmonic motion as a spring, with . So the period is
and, curiously, the mass has dropped out. This is a small-angle approximation; large swings take a little longer.
In the tests, a m pendulum built in the engine matched this formula to within .
Hanging chains and upside-down arches
What shape does a chain take when you hold it by both ends? In 1638, in his Two New Sciences, Galileo Galilei wrote that it is very close to a parabola, practically indistinguishable when the ends slope at less than 45°. But it is not exactly a parabola, as the German Joachim Jungius proved in work published after his death, in 1669. So what is it? Jakob Bernoulli posed the problem in 1690, and in 1691 Gottfried Leibniz, Christiaan Huygens and Jakob's younger brother Johann Bernoulli each published a solution. The curve is called the catenary, .
Meanwhile in London, Robert Hooke, who was involved in rebuilding St Paul's Cathedral after the Great Fire, was thinking about the best shape for an arch. In 1671 he told the Royal Society he had found it, and in 1675 he published the answer as a scrambled Latin anagram. Publishing the answer in code, to be decoded later, was a crafty 17th-century way of claiming priority without giving the secret away; Galileo and Huygens used it too. It was decoded only in 1705, after his death: "As hangs a flexible cable so, inverted, stand the touching pieces of an arch." Turn a hanging chain upside down and you get an arch that perfectly carries its own weight. Around the turn of the 20th century, the Spanish architect Antoni Gaudí hung models made of strings and weights and studied them upside down to design the arches and columns of a church.
Watch the bridge sag and the catenary turns up again. A bridge of planks pinned end to end behaves like a chain held at both ends, so with nothing on it, it sags into something close to a catenary. In a real suspension bridge, though, the heavy road deck hangs from the cables and loads them evenly along the horizontal. Then the cable's shape is not a catenary but very nearly a parabola: the curve Galileo offered as an approximation fits a suspension-bridge cable even better than it fits a hanging chain. The great arch in St. Louis, on the other hand, is a "weighted" catenary, adjusted because it gets thinner toward the top.
Waves along the spring chain
The row of beads is different from the rope and the chain. Neighboring beads are joined by distance joints. A distance joint can act as a rigid rod that keeps two points a fixed distance apart, or as a spring that stretches and compresses. Here they are springs, with a natural length of times the bead spacing. So the row starts out under tension, and when you shake one end, a transverse wave travels along it.
Where does the speed of a wave along a string come from? Take a short piece of string of length and mass under tension . If the string is straight, the pulls at its two ends cancel. If it is curved, they point in slightly different directions and leave a sideways force.
For small slopes, the sideways part of the tension is , where the slope is taken with time held fixed. The difference between the two ends is
proportional to the curvature. Newton's law then gives the wave equation
Try a wave that keeps its shape while moving at speed , : the left side becomes and the right side , so , and the wave travels at
The tighter and lighter the string, the faster the wave. A row of beads follows this smooth-string formula only for waves much longer than the bead spacing.
Strings and their waves have their own history. In 1636 the French friar Marin Mersenne set out the rules for a stretched string: its frequency is inversely proportional to its length, proportional to the square root of the tension, and inversely proportional to the square root of the mass per unit length. In 1747 Jean le Rond d'Alembert derived the wave equation above from the motion of a vibrating string.
The wave on the row of beads is the same physics as a vibrating guitar or violin string. A string's pitch depends on its length, its tension and its thickness, meaning its mass per unit length, and Mersenne's rules follow directly from the wave speed together with the wavelength fixed by the string's length.
Physics engines beyond the sandbox
Planck.js, the engine used here, is a JavaScript translation of Box2D, a two-dimensional physics engine written by Erin Catto. Box2D first appeared as a small teaching version to go with a talk at the 2006 Game Developers Conference, and became open-source software in 2007.
Physics engines aren't only for games. They move cloth, hair and collapsing buildings in film effects, and they let engineers try out how a robot walks or grips before building it. Working out the forces on and motions of machine parts, known as multibody analysis, uses the same ideas. Box2D and its ports have been used in many browser games and phone games, so you have probably met its calculations somewhere already.
But remember that all of these are approximations. Game engines put looking plausible, running fast and never blowing up ahead of exactness, and they may tolerate a little energy creeping in or out. In engineering and research, people choose the time step and method carefully and compare the results with experiments and theory. When this simulation's tests compare free fall and a pendulum's period with the formulas, that's a small example of the same habit. And worrying about joints that drift and errors that depend on the time step is exactly the kind of thinking you meet when you study numerical approximation in mathematics or computing.
Play in the sandbox
- When the page opens, the weight on the end of the hanging rope drops and starts to swing. How does the shape of the rope change? Picture how an ordinary pendulum on a straight string would swing, and compare.
- Drag the weight, shown as a dashed ring, up and let it go. The purple dashed line is the mouse joint, an invisible spring between your finger and the weight.
- Set "Gravitational acceleration " to 0 and swing the rope. What's different?
- Under "Preset", choose "Bridge (16 planks)" and press "⬇ Drop an object" a few times. Where does the bridge sag most? How does "Largest pin (revolute joint) separation" change?
- Choose "Row of beads on springs ()". Quickly move the second bead from the left up and down, then let go. The fixed beads at the two ends are about 9 m apart. Time how long the wave takes to reach the right end with t in the toolbar, and estimate the wave speed. What happens to the wave there?
- Choose "Chain (14 boxes)", grab one end and crack it like a whip. How does the other end move?
What the model assumes: the calculation is two-dimensional, so densities are masses per unit area . Joints are only approximately satisfied by an iterative solver and stretch slightly under a hard pull. Bounciness and friction in collisions are rough values, and energy is not conserved exactly.
What sticks and pins teach us
A physics engine solves Newton's equation of motion again and again in short time steps, enforcing the promises called joints with impulses, so that many bodies move together. A rope, a chain or a bridge is nothing but short rigid pieces pinned together, yet as a whole it behaves very much like the real thing. The answers are always approximate, though, and depend slightly on the step size and the number of solver iterations. That's exactly why it matters to check the engine against cases where we know the answer, like free fall and the pendulum.
Mathematicians racing to find the shape of a chain, an experimenter who hid the secret of the arch in an anagram, a theorist who wrote mechanics without a single figure: the sandbox you are swinging around with your finger stands on all of them. A last question: if you doubled the number of sticks in the rope and halved their length, how would the rope behave? More like a real cord? And what would become harder for the computer?
Sources and further reading
The facts in this article were checked mainly against the following.
- MacTutor, "Lagrange: Analytical Mechanics" (University of St Andrews): the "no figures" preface and multipliers for constraint forces
- Box2D (official site, by Erin Catto)
- planck.js (GitHub): the JavaScript rewrite of Box2D used in this simulation
Further reading (encyclopedias):
- Wikipedia, "Catenary": Galileo, Jungius, the three solutions of 1691, Hooke's anagram, Gaudí, weighted catenary arches, suspension-bridge cables
- Wikipedia, "Anagram": 17th-century scientists, including Galileo and Huygens, claiming priority with anagrams
- Wikipedia, "Two New Sciences": Galileo's book of 1638
- Wikipedia, "Church of Colònia Güell": Gaudí's hanging model
- Wikipedia, "Mersenne's laws": the 1636 rules for vibrating strings
- Wikipedia, "Wave equation": d'Alembert's paper of 1747
- Wikipedia, "Euler method": Euler's method (1768–1770)
- Wikipedia, "Semi-implicit Euler method": why the plain method tends to gain energy while the velocity-first method nearly conserves it
- Wikipedia, "Box2D": the 2006 talk, the 2007 release, use in games