AgentGames

Search titles, descriptions, models and tags. Press Enter to see results.

🧲 Guide

How to make a physics game with AI

A physics game is a loop that runs more often than the screen refreshes. Get that loop right and balls stop teleporting through walls.

Updated 5 October 2026 7 min read By the Agent Games team
Jump to a section
  1. Four steps to a sandbox that behaves
  2. Tunnelling, and why a thin wall is a bad wall
  3. What the fixed step actually buys you
  4. Why stacking boxes is harder than it looks
  5. Write the physics rather than importing it
  6. Common questions
  7. Where to go next

Ask for a sandbox with a floor, thick walls, a few crates and one heavy ball you can fling. Then ask for the simulation to advance in small fixed slices, several times per frame, rather than once by the frame time. That single instruction prevents most of what goes wrong in a physics build.

Collision only ever asks where a body is now

An overlap test compares two shapes at one instant. It knows nothing about the path either one took to get there. Move a ball far enough in one update and it is in front of the wall, then behind it, and was never inside it. That is tunnelling, and no amount of better overlap maths repairs it. The repair is to move less per update.

Four steps to a sandbox that behaves#

Paste the prompt below and open the result

You want the floor, the walls, a stack of crates and the fling in version one. Everything after that is tuning.

Fling the ball as hard as the controls allow

Aim at a wall. If it ever ends up outside the scene, the step is too long for the geometry. This is the only test that matters at first.

Leave the stack alone and watch it

Boxes at rest should stop dead. If they tremble or sink, the resting rule is missing rather than the collision being wrong.

Switch tabs for ten seconds and come back

A scene that explodes on return has an uncapped delta feeding the loop. One clamp fixes it, and every build needs it.

PromptCopy this, paste it, send it
Build a physics sandbox as ONE self-contained .html file. No
frameworks, no physics library, no images.

SCENE: a floor, a left wall and a right wall, drawn as canvas
rectangles. Every wall and the floor is at least 40 pixels thick, never
a thin line. Five square crates sit stacked on the floor at the right.

BODIES: every crate has a position, a velocity and a mass. Treat them as
squares that slide but do not rotate. Gravity pulls them down. Contact
with the floor or with another crate stops them. A friction value bleeds
horizontal speed while a crate is supported.

LAUNCH: drag anywhere on the left half and release to fling a heavy ball
along the drag direction. Drag length sets the launch speed. The ball
pushes crates it strikes, and the push scales with the two masses.

FIXED STEP. Treat this section as the point of the build. Never advance
the simulation by the frame time. Keep an accumulator of leftover
seconds. Add the frame time to it. While the accumulator holds at least
STEP seconds, advance every body by exactly STEP and subtract STEP from
the accumulator. Set STEP to one two hundred and fortieth of a second.
Stop after MAX_STEPS iterations in a frame so a slow frame cannot stall
the page.

SWEEP: before moving a body in a step, compare the distance it is about
to cover against WALL_THICKNESS. If the distance is larger, split that
movement into smaller pieces and test each piece in turn. A fast ball
must never appear on the far side of a wall.

RESTING: when a body's speed drops below SLEEP_SPEED while supported,
set its speed to zero. Without this a stack shivers forever.

HUD: show the steps taken this frame and how many bodies are at rest, so
the loop is visible while playing.

PHONE: a drag on the canvas is a launch. Include
canvas { touch-action: none; } in the CSS so dragging never scrolls
the page.

TIMING: measure the seconds between this frame and the last, clamp that
measurement to 0.05 before it reaches the accumulator, and never pass it
to a body as a step.

CONFIG: one object at the top of the script holding GRAVITY, STEP,
MAX_STEPS, RESTITUTION, FRICTION, SLEEP_SPEED, WALL_THICKNESS and
BALL_MASS, with a one line comment on each.

GRAVITY, RESTITUTION, FRICTION and BALL_MASS are the fun ones and want playing with. STEP and MAX_STEPS are structure, so change them only if you understand what you are trading. WALL_THICKNESS has to stay larger than the furthest any body travels in one step, which is the whole reason it is in CONFIG at all.

Tunnelling, and why a thin wall is a bad wall#

Picture a ball crossing 900 pixels in a second on a screen running at sixty frames. Each update moves it about fifteen pixels. Now give it ten times the speed. Each update moves it 150 pixels. A wall drawn two pixels wide sits entirely inside that jump, and no test taken before or after the move finds an overlap.

One big step, or several small ones The same ball at the same speed, inside the same single frame. One step of the frame time x += vx * dtClears the wall in a single hopThe overlap test never sees a hit Eight steps of a fixed slice x += vx * STEP, eight timesEach slice is thinner than the wallThe hit lands inside slice three Nothing runs faster. The same frame is simply examined more often.
The right hand side is not slower or cleverer. It simply looks at the same stretch of time more often, and the wall is wider than any single look.

There are two honest fixes and you want both. The first is the fixed step. Advance the simulation by a small constant slice, as many slices as the frame has time for. If each slice moves the ball twenty pixels, a forty pixel wall can never be missed.

The second is geometry. Make walls thick relative to the fastest thing in the scene, and never model a boundary as a line. Forty pixels of solid rectangle costs nothing to draw and removes a whole class of fault. If you want a thin look, draw a thin highlight on top of a thick collider.

A sweep is the backstop for the rest. Before moving a body, compare how far it is about to go with the thinnest thing it could hit. If the move is longer, chop it into pieces and test each. This is cheap because it only triggers on the few bodies that are genuinely racing.

What the fixed step actually buys you#

Frame times are not stable. A browser hands you sixteen milliseconds, then forty, then four. Feed those straight into a simulation and the result changes with the weather. Two players doing the same thing watch different outcomes, and neither can report a reproducible fault.

The accumulator pattern separates the two clocks. Measure real elapsed time, add it to a store, and spend that store in equal slices. Leftovers stay in the store for next frame. Every slice is identical, so the simulation stops caring how often the screen refreshes.

Frame tookSlices of 1/240s spentLeft in the store
16.7ms, a normal frameFourA fraction of a slice
4.2ms, a fast monitorOneAlmost nothing
40ms, a stutterNine or tenA fraction of a slice
Six seconds, a background tabClamped to the step limitDiscarded by the clamp

The last row is why the clamp exists. Without it a tab left open overnight tries to catch up on hours of physics in one frame.

Keep the step cap modest. Eight slices a frame is plenty for a sandbox of this size. A cap that is too generous turns one slow frame into a slower one, and the loop falls further behind on every pass.

Why stacking boxes is harder than it looks#

Bouncing one ball is easy. Resting five crates on each other is the part that defeats most first builds, and the reason is a chain. Each box pushes on the one below, and the one below pushes back. A solver that handles a single pair at a time never finds a position satisfying all of them.

Where a first physics build goes wrong Five faults, and the line of the loop each one is pointing at. 1 Passes through walls The step is longer than the wall is thick. 2 Stack never settles Resting bodies keep a tiny speed and shiver. 3 Boxes sink into the floor Overlap gets detected but never pushed back out. 4 Everything flies apart A slow frame feeds one enormous delta into the step. 5 Heavy hits feel light Momentum ignores mass, so a ball bounces off a crate. Four of the five are the step. Sort the step before touching anything else.
Read it as a diagnosis list. The symptom you can see rarely sits next to the line that caused it.
  • Push out of overlap, do not only reverse speed. If two shapes already intersect, move them apart by the overlap before anything else. Reversing velocity leaves them stuck inside each other.
  • Resolve from the bottom up. Sort resting bodies by height and settle the lowest first. The box on the floor has a fixed answer, and that answer gives the next box one too.
  • Let bodies sleep. Below a small speed threshold, with support beneath, set velocity to zero and skip the body. Jitter in a stack is almost always a body never quite reaching rest.
  • Skip rotation to begin with. Squares that slide but never turn cover most of what a sandbox needs. Rotating bodies need torque, inertia and contact points, which is a different project.
  • Keep bounciness low on resting shapes. A restitution value near one is fine for a ball. On a crate it makes the whole stack hum.

Write the physics rather than importing it#

Asking a model for a physics library in a single file build is a poor trade. A library arrives as a script tag from a network you do not control, which breaks the one property that makes these games easy to share. It also brings an API the model half remembers, and the errors come from inside code you cannot read.

Written out longhand, the whole simulation for squares and circles is short. Gravity is one addition. Overlap between two axis aligned boxes is four comparisons. An impulse between two masses is a few lines of arithmetic. All of it sits in the file, so every number is yours to move.

The exception is a scene that genuinely needs rotating bodies, joints and friction between irregular shapes. That is real engine territory, and at that point the single file approach is the wrong shape for the project. For a sandbox of boxes and balls, longhand wins on every count.

🧲Physics games written by AI

Common questions#

Why do fast objects pass through walls?

Because collision is a test at one instant, not along a path. In one update the object moves further than the wall is thick, so it is in front, then behind, and never inside. Shorten the update or thicken the wall, and ideally do both.

What is a fixed timestep and why does it matter here?

It means advancing the simulation by a constant slice of time, as many slices per frame as real time allows. Physics is sensitive to step size in a way that drawing is not. A constant slice makes results repeatable and keeps each move small enough to catch collisions.

How small should the step be?

One two hundred and fortieth of a second is a sensible start for a sandbox of boxes and balls. That is a starting point, not a rule. The real test is whether the fastest body in your scene moves less per step than the thinnest wall is thick.

Why does my stack of boxes vibrate instead of settling?

Resting bodies are keeping a very small velocity, which gets resolved, reapplied and resolved again. Add a sleep rule: below a small speed, with something supporting the body, set velocity to zero and leave it out of the solver until it is disturbed.

Should I use a physics library?

Not for a single file browser game. A library means an external script, an API the model may misremember, and failures inside code you cannot inspect. Gravity, box overlap and mass based impulses are short enough to write out, and then every value is in your CONFIG.

Why does everything explode after I switch tabs?

A background tab stops handing out frames, so the next measured gap is seconds rather than milliseconds. That gap enters the loop as one giant step and bodies move a long way at once. Clamp the measured time to a small ceiling before it reaches the simulation.

Where to go next#

A sandbox is worth publishing earlier than a game with a win condition, because people enjoy poking at one. Put it up and the page records the model and the prompt behind it. The physics builds here are a quick way to see which tricks held together.

The general method lives in how to make a game with AI. If what you actually want is a character jumping between ledges, the timers behind that are in the platformer guide. Drawing, cameras and canvas sizing are in the 2D guide, and fixes you can paste are in the prompt guide.