Every physics game is the same loop running over and over: work out the forces, move everything, find out what is touching, and decide what happens next. That is genuinely all of it. The variety in the genre comes from which forces are included and how the results are presented, not from fundamentally different machinery.

This guide walks through that loop in the order the computer does it, using the engine behind the games on this site as the worked example. No mathematics beyond multiplication is required.

The loop, step by step

A single pass through a physics engine does four things in a fixed order. Changing that order changes the behaviour, sometimes dramatically.

  1. Accumulate forces. Gravity, drag, springs, player input, force fields — everything that pushes on an object this instant is added up into a single force vector per object.
  2. Integrate. Turn that force into a change in velocity, and the velocity into a change in position.
  3. Detect collisions. Find every pair of objects that now overlap, and for each pair work out where they touch and which way to push them apart.
  4. Resolve collisions. Apply impulses so the objects bounce, rub and separate convincingly, then nudge them apart so they are not left overlapping.

Then the forces are cleared and the whole thing runs again. On this site that happens 120 times a second, regardless of how often the screen is redrawn.

Why forces are cleared every step

A force represents a push happening right now. If you did not clear the accumulator, last frame's gravity would still be there next frame, and the frame after, and objects would accelerate without limit. Impulses are different — they act instantly and are not accumulated at all.

Forces versus impulses

This distinction confuses more people than any other part of game physics, and it is worth getting straight because it explains a lot of game behaviour.

A force is a continuous push. It is applied over time, and its effect depends on how long it acts. Gravity is a force: it pulls constantly, and the longer you fall, the faster you go.

An impulse is an instantaneous change in momentum. It happens all at once. A collision is an impulse; so is a jump, in most games.

ForceImpulse
Acts overTimeAn instant
UnitsNewtons (mass × acceleration)Newton-seconds (mass × velocity)
ExampleGravity, drag, a springA bounce, a jump, an explosion
In codebody.applyForce(x, y)body.applyImpulse(x, y)
Cleared each stepYesNo — it is applied immediately

Getting this wrong produces recognisable bugs. Applying a jump as a force gives a floaty, gradual lift-off; applying gravity as an impulse makes objects fall at a constant speed instead of accelerating.

Try it: Newton's Playground

A sandbox with a job to do: spawn, flick, change gravity, fill the collector.

Play Newton's Playground

Integration: turning force into motion

Integration is the step that actually moves things. The simplest version is two lines:

velocity += (force / mass) * dt
position += velocity * dt

That is called semi-implicit (or symplectic) Euler integration, and the order matters enormously. Velocity is updated first, so the position step uses the new velocity.

Why the order matters

If you update position first and velocity second — explicit Euler — the simulation quietly adds energy over time. A pendulum swings progressively higher. An orbit spirals outward. A stack of boxes starts to jitter and then explodes.

Swapping two lines fixes it. This is one of the highest value-per-character changes in all of game programming.

Fixed timesteps

Real frames arrive at irregular intervals. If dt varies, the simulation produces different results on different hardware, and a stutter can let an object pass straight through a wall.

The standard solution is an accumulator. Each frame, the elapsed time is added to a running total, and the simulation steps by a fixed amount as many times as that total allows. Any remainder waits for next frame.

accumulator += frameTime
while (accumulator >= FIXED_DT) {
  step(FIXED_DT)
  accumulator -= FIXED_DT
}

The spiral of death

If each step takes longer than the timestep it simulates, the accumulator grows faster than it drains and the game freezes. Every production implementation caps the number of steps per frame and discards the backlog — which is also why switching browser tabs and coming back does not fast-forward the game.

Collision detection

Once everything has moved, some objects are overlapping. Finding them efficiently is a bigger problem than it first appears.

Broad phase

Testing every object against every other is O(n²): ten objects means 45 tests, a hundred objects means 4,950. The broad phase cheaply eliminates pairs that are nowhere near each other, usually by comparing simple bounding boxes or by bucketing objects into a grid.

The engine on this site uses brute force below about forty bodies — where the simpler approach is genuinely faster — and switches to a uniform spatial hash above that.

Narrow phase

For the handful of pairs that survive, the narrow phase works out the exact contact: whether they really overlap, by how much, at what point, and along which direction they should be pushed apart.

  • Circle versus circle is trivial: compare the distance between centres against the sum of the radii.
  • Circle versus polygon finds the closest point on the polygon's edges to the circle's centre.
  • Polygon versus polygon uses the Separating Axis Theorem: if there is any direction along which the two shapes' shadows do not overlap, they are not touching.

The output is a contact manifold: which two bodies, the contact normal, how deep the overlap is, and where the contact point sits.

Collision response

Knowing two objects are touching is the easy part. Deciding what should happen next is where a physics engine earns its keep.

The normal impulse

First the engine computes the relative velocity of the two bodies along the contact normal. If they are already separating, nothing needs doing. If they are approaching, an impulse is applied to reverse that approach, scaled by the restitution — how bouncy the pair is.

Crucially, the impulse is divided between the two bodies in inverse proportion to their masses. A ping-pong ball hitting a wall gets almost all the velocity change; the wall (with effectively infinite mass) gets none.

The friction impulse

A second impulse is applied along the surface rather than perpendicular to it. Its size is capped by the normal impulse times the friction coefficient — Coulomb's model — which is why heavier objects are harder to slide.

Positional correction

Impulses change velocities but not positions, so overlapping objects stay overlapped for a frame. A small positional nudge afterwards pushes them apart, with a deliberate tolerance (the 'slop') so resting objects do not vibrate.

Why stacks need multiple iterations

Resolving one contact can break another. In a stack of five boxes, pushing box three up may push box four into box five. Engines therefore run the resolution several times per step — this one runs it six to nine times depending on the game — letting the solution converge. It is why Stack Physics can hold a twenty-storey tower without jitter.

Try it: Stack Physics

Drop crates from a moving crane and build a tower that stays standing.

Play Stack Physics

Constraints: ropes, rods and pivots

Forces and collisions cover most of a physics game, but some relationships are better expressed as rules than as pushes. A rope should hold two things a fixed distance apart; a hinge should let a door rotate but not translate.

These are constraints, and they are usually solved positionally rather than through forces. Instead of applying a very stiff spring and hoping, the solver simply moves the objects until the rule is satisfied, then removes the velocity that was violating it.

Why not just use a stiff spring?

You can, and it fails badly. A spring stiff enough to behave like a rope needs a timestep small enough to resolve its oscillation, and at normal game timesteps it explodes. A positional constraint has no such problem: it is exact by construction.

That is why Rope Swing feels taut rather than rubbery, and why the rope visibly goes slack the moment you move towards its anchor — a rope constraint is one-way, and the solver simply does nothing while the distance is under the limit.

Solving in sequence

A chain of constraints cannot generally be solved in one pass, because fixing link three moves link four. The standard approach is Gauss-Seidel: run through all the constraints repeatedly, fixing each in turn, and let the whole system converge over several iterations.

This is the same reason the collision solver runs multiple times per step, and the same reason a rope with more segments needs more iterations to look convincing.

Why a pendulum gets its own model

A pendulum could be built from a rope constraint, but integrating the angle directly — θ'' = −(g/L)·sin θ — gives repeatable timing that a constraint chain cannot match. When the gameplay depends on a stable period, as in Pendulum Puzzle, the explicit model is worth the extra code.

Keeping a simulation stable

A physics engine that is merely correct is not yet usable. Three further problems have to be solved before it stops looking broken.

Jitter

Objects at rest tend to vibrate, because the solver keeps detecting a tiny overlap, pushing them apart, and letting gravity pull them back. The standard fixes are a slop tolerance — ignore overlaps below a threshold — and a rest threshold on restitution, so a contact below a certain closing speed is treated as resting rather than bouncing.

Without that second fix, a ball dropped on a floor bounces infinitely at ever-smaller amplitudes and buzzes forever.

Sinking

Impulses change velocity, not position, so objects that overlap stay overlapped for at least a frame — and in a stack, the errors accumulate downward. A positional correction pass afterwards pushes them apart, applied gently so it does not itself add energy.

Non-finite values

One divide-by-zero anywhere in a simulation produces a NaN, and a NaN propagates through every subsequent calculation until the whole world disappears. Production engines sanitise: if a body's position stops being a finite number, it is reset to its last known good state rather than allowed to poison everything else.

A practical debugging rule

If a physics scene explodes, the cause is almost always one of four things: a timestep that is too large, a mass that is zero when it should not be, a constraint that is over-stiff, or an object that started out already overlapping another. Checking those four in order solves most cases.

What every arcade engine simplifies

A real-time game engine is a set of deliberate approximations. These are the ones almost every arcade physics engine makes.

  • Restitution is a constant. In reality it varies with impact speed — drop a ball harder and it returns proportionally less.
  • Contacts are points. Real contacts are areas, which is why a real box resting on a floor is far more stable than a simulated one.
  • Air resistance is linear or absent. True drag rises with the square of speed and depends on shape.
  • Rotation is simplified. Many arcade bodies have rotation locked entirely, because a rolling player character is usually less fun than a sliding one.
  • Collisions are discrete. Objects are tested after they move, so a very fast small object can pass through a thin wall. Continuous detection exists but is expensive.

None of these are mistakes. They are the price of running sixty times a second inside a browser tab, and in almost every case the approximation is invisible during play.

Key takeaways

  • Every physics engine runs the same four-step loop: accumulate forces, integrate, detect collisions, resolve them.
  • Forces act over time; impulses act instantly. Mixing them up produces recognisable bugs.
  • Semi-implicit Euler — velocity before position — is what keeps simulations stable.
  • A fixed timestep with an accumulator makes the game behave identically on any hardware.
  • Collision is split into a cheap broad phase and an expensive narrow phase.
  • Stacks need the solver to run several times per step so contacts can converge.

Frequently asked questions

What does a game physics engine actually do?

Each step it gathers the forces acting on every object, uses them to update velocities and positions, finds which objects now overlap, and applies impulses to separate them convincingly. Everything else is built on those four operations.

Why do physics games use a fixed timestep?

So the simulation behaves identically regardless of frame rate. With a variable timestep, a 30fps phone and a 144Hz monitor would produce different jump heights and different collision outcomes.

What is the difference between a force and an impulse?

A force is a continuous push whose effect depends on how long it acts; an impulse is an instantaneous change in momentum. Gravity is a force, a bounce is an impulse.

Why do objects sometimes pass through walls in physics games?

Because collisions are usually detected after objects move. If something travels further than a wall is thick in a single step, the overlap never occurs. Smaller timesteps and continuous collision detection reduce it, at a cost.

What is a contact manifold?

The output of collision detection: which two bodies are touching, the direction to push them apart (the normal), how deep the overlap is, and where the contact point sits.

References