Web Games From Zero · Episode 04

Platformer Physics

Platformer Physics is Episode 04 of Web Games From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 04 · Web Games From Zero

The difference between a platformer that feels amazing and one that feels like running through mud is not the art, not the engine, and not some secret you need a studio to know. It's about eight numbers — and four small tricks layered on top of plain gravity. Mario, Celeste, Hollow Knight, Super Meat Boy: under the hood they're all running the same handful of ideas you're about to write yourself, in a single file, with raw canvas 2D and zero dependencies.

By the end of this page you'll have a jump that feels great — and you'll know exactly which knob does what, because every one of them is a live slider in the demo below. Asymmetric gravity, variable jump height, coyote time, jump buffering, acceleration and friction, one-way platforms. Step through the six stages and feel each fix land. The little box even plays the level by itself until you grab the keys.

0 fps
▶ playing demo — press any key (or ← → / Space) to take over
fixed step · 60 Hz
A box falls and lands on the floor. That's gravity + an AABB ground check — frame zero of every platformer.

What you're looking at

One box, one world, six progressively-better feel models. The box is the player. The thick bar is the ground; the thin bars in later stages are platforms. The stage dropdown swaps which feel features are turned on, mapped one-to-one to the sections below — so you can feel the difference each trick makes instead of taking my word for it. The sliders are the eight numbers. Drag gravity low and the jump turns to helium; drag it high and the box slams down like it's made of lead.

While you're reading, the demo plays itself — a tiny scripted "AI" walks, jumps gaps, and rides platforms so the box is never just sitting there dead. The moment you press ← → or Space (or A/D/W), you take over. Toggle attract back on to hand control back to the demo. The crucial part: the demo and you drive the exact same physics code — there's no separate "demo mode" simulation, just a function that fakes button presses.

The one habit that makes jumps consistent: the fixed timestep

Before a single number matters, the loop has to be right. If you move the player by velocity * dt with whatever dt the browser hands you, your jump will reach a different height on a 60 Hz laptop than on a 144 Hz monitor, and a different one again when the frame rate dips. Jump feel is the sum of tiny per-frame decisions; it cannot survive a wobbling timestep.

So we don't use a variable dt for physics. We accumulate real elapsed time and consume it in fixed slices of exactly 1/60 of a second, running update(STEP) zero-or-more times per frame, then render once. Every physics number in this episode is tuned against that constant STEP, which is why the jump feels identical on any machine:

const STEP = 1 / 60;                 // fixed simulation step (seconds)
let acc = 0, last = performance.now();
function loop(now) {
  let dt = (now - last) / 1000; last = now;
  if (dt > 0.25) dt = 0.25;          // clamp tab-switch gaps (no spiral of death)
  acc += dt;
  while (acc >= STEP) { update(STEP); acc -= STEP; }   // 0..n fixed updates
  render();
  requestAnimationFrame(loop);
}
requestAnimationFrame(loop);

Hold this thought for the rest of the page: inside update, STEP is a constant. We never multiply movement by a variable frame time. That single discipline is what lets the eight numbers below mean something.

Stage 1 — Gravity + ground

The simplest possible world. The box has a vertical velocity vy; every step gravity adds to it, and the velocity moves the box. Left alone it would fall forever, so after moving we check whether the box's bottom has crossed the floor — a one-axis AABB (axis-aligned bounding box) test — and if so, we snap it to the surface and zero out vy. That "snap, then zero" is the heart of standing on ground, and it's the same check we'll reuse for every platform.

Here's the core update — gravity, the move, the ground check, plus the horizontal motion we'll flesh out in Stage 5. Notice STEP everywhere and not one variable dt:

// (a) the platformer update — runs once per fixed STEP
function update(dt) {                 // dt is ALWAYS the constant STEP
  const input = readInput();        // {left, right, jump, jumpHeld}

  // --- horizontal: accelerate toward a target, else apply friction ---
  const dir = (input.right ? 1 : 0) - (input.left ? 1 : 0);
  if (dir !== 0) {
    p.vx += dir * ACCEL * dt;                 // ramp up, don't snap
    p.vx = clamp(p.vx, -MAX_RUN, MAX_RUN);
  } else {
    const drop = FRICTION * dt;               // ease back to zero
    p.vx = p.vx > 0 ? Math.max(0, p.vx - drop)
                       : Math.min(0, p.vx + drop);
  }

  // --- vertical: gravity is just a constant acceleration ---
  p.vy += GRAVITY * dt;

  // --- integrate, then resolve collisions axis by axis ---
  p.x += p.vx * dt;
  resolveX();
  p.y += p.vy * dt;
  p.grounded = false;
  resolveY();                                  // snaps to ground, sets p.grounded
}

That's a working platformer. It is also, honestly, not fun yet — but it never falls through the floor, and that's the foundation. Everything from here is feel.

Stage 2 — Basic jump (and why it feels off)

Add jumping the obvious way: if the box is on the ground and the player presses jump, set vy to a fixed upward impulse. Gravity does the rest — up, slow, peak, down. Switch to Stage 2 and try it.

It works… and it feels wrong. Two problems you can feel immediately. First, the jump is all-or-nothing: a tap and a long hold give the exact same height, so you can't do a careful little hop. Second, the arc is symmetric — the box takes just as long coming down as going up, which reads as floaty, like the moon. Real-feeling jumps are lopsided: a quick rise and a faster, snappier fall. Hold that complaint; the next stage fixes both with about six lines.

A symmetric parabola is physically correct and emotionally dead. Almost no beloved platformer uses real gravity. The fun is in the lie.

Stage 3 — Variable height + a better fall

Two independent fixes, both about gravity asymmetry.

Variable jump height. While the box is rising, if the player releases the jump button, we cut the upward velocity short — clamp vy to a fraction of itself. Tap for a hop, hold for a full leap. This one change is the single biggest jump-feel upgrade there is, and it's nearly free.

Asymmetric fall gravity. We apply stronger gravity when the box is moving downward (and a touch extra when rising but no longer holding jump). The rise stays floaty enough to aim; the fall is quick and decisive. Together these turn the moon-jump into the snappy arc every good platformer has:

// (b) variable jump height + asymmetric fall gravity
const FALL_MULT     = 1.9;   // gravity ×1.9 while falling — snappy descent
const LOW_JUMP_MULT = 2.4;   // extra gravity when rising w/ button released
const CUT          = 0.45;  // keep 45% of vy when the jump is cut short

// pick a gravity scale based on motion + whether jump is held
let g = GRAVITY;
if (p.vy > 0)            g *= FALL_MULT;        // vy > 0 means falling (y is down)
else if (!input.jumpHeld) g *= LOW_JUMP_MULT;   // rising but released → arc over sooner
p.vy += g * dt;

// cut the jump the instant the button is released on the way up
if (!input.jumpHeld && p.vy < 0) {
  p.vy *= CUT;                                 // short hop instead of full leap
}

Flip between Stage 2 and Stage 3 a few times. The numbers are the same; only the asymmetry changed. That's the whole secret of a snappy jump.

Stage 4 — Coyote time + jump buffering

Now the forgiveness windows — the tricks that make a jump feel responsive even though human timing is sloppy. Without them, a technically-correct platformer feels subtly broken and players blame themselves.

Coyote time (named after the cartoon coyote who hangs in the air a beat before falling): for a few frames after the box walks off a ledge, it's still allowed to jump. You've all felt the bad version — you press jump right at the edge, nothing happens, you fall. Coyote time fixes exactly that.

Jump buffering: if the player presses jump a few frames before landing, we remember the press and fire it the instant the box touches down. Without it, an early press is swallowed and the box just sits there. Both are tiny countdown timers:

// (c) coyote time + jump buffering — two small timers
const COYOTE_MAX = 6;    // frames you can still jump after leaving ground
const BUFFER_MAX = 6;    // frames an early press stays "remembered"

// each step: refill coyote on the ground, otherwise count it down
if (p.grounded) coyote = COYOTE_MAX;
else            coyote = Math.max(0, coyote - 1);

// remember a fresh jump PRESS (edge, not hold) for a few frames
if (input.jumpPressed) buffer = BUFFER_MAX;
else                   buffer = Math.max(0, buffer - 1);

// a jump happens when a buffered press meets a coyote window
if (buffer > 0 && coyote > 0) {
  p.vy   = -JUMP_FORCE;
  buffer = 0;            // consume the press
  coyote = 0;            // can't double-jump off one window
}

Crank the coyote slider to 0 in Stage 4 and try to jump right as you leave a ledge — it feels stiff and unfair. Bump it to 6 and the same input "just works." Six frames is one tenth of a second: invisible to the eye, enormous to the hands.

Stage 5 — Acceleration, friction, and one-way platforms

Two more feel ingredients. Momentum: the horizontal code from Stage 1 was already accelerating rather than snapping to top speed — here you can really feel it with the accel and friction sliders. Low accel = a heavy box that takes a moment to wind up; high friction = it stops on a dime. Instant velocity (just setting vx to max) feels robotic; ramping it feels alive.

One-way platforms: the thin bars you can jump up through from below but land on from above — and drop through by holding ↓. The rule is simple and it's the classic source of bugs: only collide with a one-way platform when the box is moving downward and its feet were above the platform's top on the previous step. That "was above last frame" check is what stops the box from snapping up to a platform it's rising through:

// (d) one-way platform — collide only when falling onto it from above
function resolveY() {
  for (const s of solids) {            // solids: collide from every side
    if (overlaps(p, s)) landOn(s);
  }
  for (const f of oneWays) {
    const feet     = p.y + p.h;
    const prevFeet = p.prevY + p.h;       // where the feet were last step
    const falling = p.vy >= 0;
    const wasAbove = prevFeet <= f.y + 1;     // stood above the platform top
    const wantDrop = input.down;            // holding ↓ → fall through
    if (falling && wasAbove && !wantDrop &&
        horizontallyInside(p, f) && feet >= f.y) {
      p.y = f.y - p.h;                     // snap feet to the platform
      p.vy = 0;
      p.grounded = true;
    }
  }
}

Walk off the side of a one-way platform and you fall naturally. Jump from under it and you pass straight up through it, then land on top. Hold ↓ while standing on one and you drop through. Three behaviors, one little block of conditions.

Stage 6 — A small level (everything live)

Now all of it at once: ground, floating solids, one-way platforms, gaps to clear — with every feel knob active. This is the headliner. Let the demo-AI run it: watch the box build speed, use coyote time off ledges, buffer its jumps, and ride one-way platforms up. Then press a key and play it yourself. Tune the sliders while you play and feel the character change from floaty to tight to leaden in real time.

This is the whole point of the episode. The level isn't hard. The feel is the content. A great platformer is a conversation between your hands and these eight numbers, and now you're holding both ends of it.

The eight numbers, in one table

Here's every knob, what it does, and a starting value that feels good. Treat these as a home base, then wander:

NumberWhat it controlsGood start
GRAVITYBase downward acceleration — the weight of the world2000 px/s²
JUMP_FORCEUpward impulse at takeoff — how high a full jump goes620 px/s
FALL_MULTGravity multiplier while falling — snappiness of the descent1.9×
LOW_JUMP_MULTExtra gravity rising with button released — short-hop arc2.4×
CUTFraction of vy kept when a jump is released early0.45
COYOTE_MAXFrames you can still jump after leaving a ledge6 frames
BUFFER_MAXFrames an early jump press is remembered before landing6 frames
ACCEL / FRICTIONHow fast you reach top speed / how fast you stop1800 / 2200

Common pitfalls

  • Floaty jump. The symmetric parabola. Real gravity feels like the moon. Fix it with higher fall gravity (FALL_MULT), variable height (CUT on release), and a punchy JUMP_FORCE. Drop the gravity slider to its minimum in the demo to feel the disease, then raise it.
  • No coyote time. Jumps at the edge of a ledge silently fail and the game feels unresponsive and unfair — players blame their fingers, not your code. A six-frame window cures it and is imperceptible. Set the slider to 0 to feel the bad version.
  • Instant acceleration. Setting vx straight to top speed makes the character feel like it's on rails. Ramp up with ACCEL and ease down with FRICTION so there's weight and follow-through.
  • Frame-rate-dependent physics. Moving by a variable dt makes the jump a different height at 30, 60, and 144 Hz. Use the fixed timestep and tune everything against the constant STEP. This is non-negotiable for jump feel.
  • One-way platform edge cases. Forgetting the "moving down AND was above last frame" guard makes the box teleport onto platforms it's rising through, or get stuck when walking past. Always gate one-way collisions on downward motion and the previous-frame foot position, and let ↓ disable them so the player can drop.

Exercises

  1. Double jump. Add a jumpsLeft counter, reset to 2 when grounded. On each fresh jump press (not hold) with jumpsLeft > 0, set vy = -JUMP_FORCE and decrement. Bonus: make the second jump a little weaker, and emit a puff of particles (you'll have those in Episode 05) at the apex.
  2. Wall slide + wall jump. When the box is airborne and pressed against a solid horizontally, clamp vy to a slow slide speed. If the player jumps while wall-sliding, launch them up and away from the wall (set vx to a push in the opposite direction and briefly ignore horizontal input so it reads as a real kick-off). This single mechanic is the soul of Celeste.
  3. Dash with a cooldown. On a key press, set a large velocity in the facing direction for ~8 frames, suppress gravity during the dash, then start a cooldown timer before it can be used again. Add a tiny hit-stop freeze on activation for crunch. Watch how much more capable the character instantly feels.

What's next

Episode 05 — Juice & Game Feel. The physics now feels right; next we make it feel alive. Screen shake on landing, squash-and-stretch on the jump, dust particles when you push off, a little hit-stop on impact, camera lead, trails. None of it changes the simulation by a pixel — and all of it changes everything. Same box, ten times the satisfaction. It's the most fun episode in the series.