TExcelTAD
Home › 2D Games with JavaScript & Canvas › Platformer 1: Gravity & Jumping

Platformer 1: Gravity & Jumping

Project 4 is a side-view platformer: run, jump, land on platforms, avoid spikes and reach the goal. Platformers live or die by how the jump feels, so this project spends a whole lesson on details most players never notice but always feel.

Step Lesson New ideas
1 Gravity & Jumping velocity, gravity, ground check, acceleration, variable jump height
2 Tilemaps & Tile Collision a level as an array of strings, AABB vs tiles, one axis at a time
3 Coyote Time & Jump Buffering forgiving input timers
4 Camera Follow a level bigger than the screen, smooth camera, clamping
5 Hazards, Checkpoints & Goal death, respawn, checkpoints, a win screen

Velocity and gravity

In the shooter, the ship moved at a constant speed while a key was held. A platformer character has a velocity (vx, vy) that changes over time, and gravity is just a constant acceleration added to vy every update:

js
player.vy += GRAVITY * dt;                 // accelerate downward
player.vy = Math.min(player.vy, MAX_FALL); // terminal velocity
player.y += player.vy * dt;                // then move

Updating the velocity before the position is called semi-implicit Euler integration. It's stable, cheap, and what nearly every 2D game uses. Because the course's play kit runs update at a fixed step (see The Fixed-Step Loop), the jump is exactly the same height on a 60 Hz laptop and a 144 Hz monitor.

A jump is a single instant change of velocity: vy = -JUMP_SPEED (negative is up). Gravity then slows the character down, stops it at the top of the arc and pulls it back.

The ground check

The player may only jump when standing on something. In this first step "something" is a flat floor: after moving, if the feet are below the floor line, snap them back onto it, stop the fall, and remember that we're grounded.

js
player.onGround = false;
if (player.y + player.h >= FLOOR_Y) {
  player.y = FLOOR_Y - player.h;
  player.vy = 0;
  player.onGround = true;
}

Notice that onGround is recomputed every update. Walking off a ledge or being knocked into the air makes it false automatically.

Variable jump height

In almost every good platformer, tapping jump gives a small hop and holding it gives a full jump. The simplest way: when the player releases the button while still rising, cut the upward speed. Here are a full jump and a tapped jump simulated with the same numbers as the game:

js · try it yourself
const DT = 1 / 60, GRAVITY = 1500, JUMP_SPEED = 440, CUT = 0.45;

function jump(holdFrames) {
  let y = 0, vy = -JUMP_SPEED, peak = 0, frames = 0;
  while (true) {
    frames++;
    if (frames === holdFrames && vy < 0) vy *= CUT;   // button released while rising
    vy += GRAVITY * DT;
    y += vy * DT;
    peak = Math.min(peak, y);
    if (y >= 0) break;                                 // back on the ground
  }
  return { peak: Math.round(-peak), airFrames: frames };
}

console.log('hold the whole time:', jump(Infinity));
console.log('tap (6 frames):     ', jump(6));
console.log('medium (14 frames): ', jump(14));
console.log('formula v²/2g:      ', Math.round(JUMP_SPEED ** 2 / (2 * GRAVITY)), 'pixels');
hold the whole time: { peak: 61, airFrames: 35 }
tap (6 frames):      { peak: 36, airFrames: 24 }
medium (14 frames):  { peak: 58, airFrames: 32 }
formula v²/2g:       65 pixels

The simulated full jump lands a few pixels below the textbook height v² / 2g: that is the cost of stepping in 1/60-second chunks, and it is the same on every machine. That formula is also how designers pick the numbers: decide the jump height in tiles and the time to the top, then solve for GRAVITY and JUMP_SPEED.

Running with acceleration

Setting vx straight to ±RUN_SPEED feels stiff. Accelerating toward the target speed, and slowing down with friction when no key is held, feels much more physical while still being precise:

js
const target = dir * RUN_SPEED;                 // dir is -1, 0 or 1
const rate = dir !== 0 ? ACCEL : FRICTION;
player.vx = approach(player.vx, target, rate * dt);

function approach(value, target, step) {        // move toward target by at most `step`
  return value < target ? Math.min(value + step, target) : Math.max(value - step, target);
}

Give the player less control in the air (ACCEL * 0.6) and jumps get a sense of commitment; give full control and it feels arcade-like. Both are valid choices.

Step 1: run and jump

Click the game. Arrow keys or A/D to run, Space, W or Up to jump. Tap jump for a hop, hold it for a full jump. The trail of dots shows your last arc.

html · try it yourself
<style>
  html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
  canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set();   // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
  if (!e.repeat) pressed.add(e.code);
  keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
  ctx.save();
  ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
  ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
  ctx.restore();
}
function run(update, draw, help = '') {
  const STEP = 1 / 60;
  let acc = 0, last = performance.now();
  requestAnimationFrame(function frame(now) {
    const dt = Math.min((now - last) / 1000, 0.1);
    last = now;
    if (active) {
      acc += dt;
      while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
      draw();
    } else if (!idleDrawn) {
      draw(); banner('Click to play', help); idleDrawn = true;
    }
    requestAnimationFrame(frame);
  });
}
// ---- end of play kit ----

const GRAVITY = 1500, JUMP_SPEED = 440, CUT = 0.45, MAX_FALL = 600;
const RUN_SPEED = 150, ACCEL = 1400, FRICTION = 1800, FLOOR_Y = 230;
const player = { x: 60, y: FLOOR_Y - 16, w: 12, h: 16, vx: 0, vy: 0, onGround: true, facing: 1 };
const trail = [];
let jumpWasHeld = false;

const approach = (v, t, s) => (v < t ? Math.min(v + s, t) : Math.max(v - s, t));
const jumpHeld = () => keys.has('Space') || keys.has('KeyW') || keys.has('ArrowUp');
const jumpPressed = () => pressed.has('Space') || pressed.has('KeyW') || pressed.has('ArrowUp');

function update(dt) {
  // horizontal: accelerate toward the target speed
  const dir = (keys.has('ArrowRight') || keys.has('KeyD') ? 1 : 0) - (keys.has('ArrowLeft') || keys.has('KeyA') ? 1 : 0);
  if (dir !== 0) player.facing = dir;
  const rate = dir !== 0 ? (player.onGround ? ACCEL : ACCEL * 0.6) : (player.onGround ? FRICTION : 300);
  player.vx = approach(player.vx, dir * RUN_SPEED, rate * dt);

  // jumping
  if (jumpPressed() && player.onGround) {
    player.vy = -JUMP_SPEED;
    player.onGround = false;
    trail.length = 0;
  }
  const held = jumpHeld();
  if (jumpWasHeld && !held && player.vy < 0) player.vy *= CUT;   // released early: short hop
  jumpWasHeld = held;

  // gravity, then move
  player.vy = Math.min(player.vy + GRAVITY * dt, MAX_FALL);
  player.x += player.vx * dt;
  player.y += player.vy * dt;

  // walls and floor
  if (player.x < 0) { player.x = 0; player.vx = 0; }
  if (player.x + player.w > W) { player.x = W - player.w; player.vx = 0; }
  player.onGround = false;
  if (player.y + player.h >= FLOOR_Y) {
    player.y = FLOOR_Y - player.h;
    player.vy = 0;
    player.onGround = true;
  }
  if (!player.onGround) trail.push(player.x + player.w / 2, player.y + player.h);
}

function drawPlayer() {
  const x = Math.round(player.x), y = Math.round(player.y);
  ctx.fillStyle = '#ffb74d'; ctx.fillRect(x, y, player.w, player.h);             // body
  ctx.fillStyle = '#5d4037'; ctx.fillRect(x, y, player.w, 4);                    // hair
  ctx.fillStyle = '#fff';                                                         // eyes look where we run
  const ex = player.facing > 0 ? x + 6 : x + 1;
  ctx.fillRect(ex, y + 6, 2, 3); ctx.fillRect(ex + 4, y + 6, 2, 3);
}

function draw() {
  ctx.fillStyle = '#16213e'; ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#3a6b35'; ctx.fillRect(0, FLOOR_Y, W, 4);                     // grass
  ctx.fillStyle = '#5b3a29'; ctx.fillRect(0, FLOOR_Y + 4, W, H - FLOOR_Y - 4);   // dirt
  ctx.fillStyle = '#ffffff55';
  for (let i = 0; i < trail.length; i += 6) ctx.fillRect(Math.round(trail[i]), Math.round(trail[i + 1]), 2, 2);
  drawPlayer();
  ctx.fillStyle = '#9aa4c0'; ctx.font = '11px ui-monospace, monospace'; ctx.textAlign = 'left';
  ctx.fillText(`vx ${player.vx.toFixed(0).padStart(4)}  vy ${player.vy.toFixed(0).padStart(4)}  ${player.onGround ? 'on ground' : 'in the air'}`, 8, 16);
}

run(update, draw, 'Arrows / A D to run, Space / W / Up to jump');
</script>

Experiment with the constants at the top: double GRAVITY and raise JUMP_SPEED to about 620 for a snappy, heavy jump that reaches the same height in less time; lower GRAVITY to 700 for a floaty moon jump. Many games also use stronger gravity while falling than while rising (GRAVITY * 1.6 when vy > 0), which makes jumps feel less floaty without lowering them.

Note: jumpPressed() reads the kit's pressed set, which only contains keys pressed since the last update. Holding Space therefore jumps once, not again on every landing. jumpHeld() reads keys, the set of keys held right now.

Test yourself

What does gravity change every update?

  1. The position directly
  2. The vertical velocity vy
  3. The jump button state
  4. The frame rate

How does this lesson make tapping jump give a lower jump than holding it?

  1. It uses a different gravity for taps
  2. When the button is released while rising, vy is multiplied by a factor below 1
  3. It waits to see how long the key is held before jumping
  4. It teleports the player down

Why is onGround set to false at the start of the collision check every update?

  1. To make the player fall faster
  2. So walking off a ledge or being knocked up automatically counts as airborne unless a collision proves otherwise
  3. Canvas requires it
  4. To reset the score