JavaScript Platformer Tutorial 3: Jump and Touch Controls

The trick to controls that work on a phone and on a computer is to stop thinking about devices. Every input, a key, a mouse click or a finger, gets translated into the same three actions: jump was pressed, jump is held, and face this way. The game only reads those three. In part 3 of our JavaScript platformer tutorial, Cubi gets a jump button, a swipe to turn around, and the keyboard, plus two small tricks that make jumping feel fair.

We continue from part 2, gravity and collisions. As always, only what changes is shown here, and the demo at the end has the complete file.

Step 1: the new numbers

const GRAVITY = 1500;
const MAX_FALL = 600;
const JUMP_SPEED = 600;   // px/s upward: 600² / (2 · 1500) = 120 px, almost 4 tiles
const JUMP_CUT = 200;     // letting go early caps the rise at this speed
const COYOTE = 0.08;      // seconds you can still jump after leaving a ledge
const BUFFER = 0.1;       // seconds a jump pressed too early is remembered
const SWIPE = 30;         // CSS pixels a finger must travel to count as a swipe

The jump is just a speed upward. With the gravity from part 2, how high it goes comes straight from a physics formula: h = v² / 2g, so 600 pixels per second lifts Cubi 120 pixels, almost four tiles. That is the number a level designer cares about, and it is worth writing down next to the constant.

The other four numbers are explained below, one at a time.

Step 2: one input, three actions

Everything the player does ends up in this small object and these three functions. Keyboard, mouse and touch all call them, and the game itself never knows which one was used.

const input = { jumpPressed: false, jumpHeld: false };

function pressJump() {
  // Holding a key repeats keydown: only the first one is a new jump.
  if (!input.jumpHeld) input.jumpPressed = true;
  input.jumpHeld = true;
}
function releaseJump() { input.jumpHeld = false; }
function face(dir) { player.dir = dir; }

Why keep both jumpPressed and jumpHeld? Because they answer different questions. Pressed is a moment: it is what starts a jump, and it is used once. Held is a state: it is what decides how high that jump goes, as we will see in step 6.

Turning around is just setting the direction. Cubi still turns by himself when he hits a wall, as in part 2; now you can also turn him whenever you want.

Step 3: the keyboard

const JUMP_KEYS = ['Space', 'ArrowUp', 'KeyW'];
window.addEventListener('keydown', (e) => {
  if (JUMP_KEYS.includes(e.code)) pressJump();
  else if (e.code === 'ArrowLeft' || e.code === 'KeyA') face(-1);
  else if (e.code === 'ArrowRight' || e.code === 'KeyD') face(1);
  else return;
  // Keep space and the arrows from scrolling the page.
  e.preventDefault();
});
window.addEventListener('keyup', (e) => {
  if (JUMP_KEYS.includes(e.code)) releaseJump();
});

Two details. We read e.code and not e.key: code is the physical key, so W, A and D stay in the same place on a French or a German keyboard, where those letters are somewhere else. And preventDefault() keeps the space bar and the arrows from scrolling the page, which matters a lot when the game lives inside an article, like this one.

Step 4: from the screen to the world

Before a touch can press the button there is a question to answer, and every game with a mouse or a touch screen has to answer it: where in my world did that finger land? The browser answers in page pixels. The game thinks in world units. They are not the same thing, and the gap between them is where many buttons that "sometimes do not work" come from.

Since part 1 there are three kinds of coordinates in play:

  • Page coordinates, in CSS pixels: what the browser gives us in e.clientX and e.clientY, counted from the top left corner of the window.
  • The canvas buffer, in real pixels: two or three times bigger than the CSS size on a phone, because of devicePixelRatio.
  • World units: our fixed 512 by 288, where the button, the tiles and Cubi live.

The canvas is scaled to fit the screen and centered in it, so neither its size nor its position is known in advance. That is why the conversion asks the browser every time, and takes three moves:

function toWorld(e) {
  // Where the canvas is on the page right now, and how big it looks (CSS pixels).
  const r = canvas.getBoundingClientRect();
  return {
    // Minus where it starts, divided by how big it looks (0 to 1), times the world.
    x: (e.clientX - r.left) / r.width * VIEW_W,
    y: (e.clientY - r.top) / r.height * VIEW_H,
  };
}
  1. Subtract where the canvas starts. getBoundingClientRect() says where the canvas is on the page right now. On a wide phone the game is centered between two black bars, so the left edge of the canvas is not at 0: it is wherever the bar ends.
  2. Divide by how big it looks. That turns the position into a fraction: 0 at the left edge of the canvas, 1 at the right edge, 0.5 in the middle. A fraction does not care whether the canvas measures 300 pixels or 1,500.
  3. Multiply by the size of the world. The fraction becomes world units: 0.5 is 256, on every screen.

An example with real numbers: a phone held sideways, 844 by 390 CSS pixels. The canvas fits the height, 390 high by 693 wide, and is centered, so it starts at 75. A thumb at clientX = 700 is at (700 − 75) / 693 = 0.90 of the canvas, and 0.90 × 512 = 461 in the world: right on the jump button, whose center is at 468. The same thumb on a tablet, a monitor or the small frame of this article lands on the same 461.

Notice what is not in the formula: devicePixelRatio. Pointer events and getBoundingClientRect() both speak in CSS pixels, so the size of the buffer never enters the conversion. Mixing it in is the classic reason a game's buttons work on a computer and miss on a phone, where the ratio is 3 instead of 1. And the rectangle is read on every touch instead of being saved once: rotating the phone, resizing the window or scrolling the page around the demo all move it.

This small function will come back in every part. In part 4 the camera adds one more step, from the screen to the level, and with that any tap can answer "which tile, which enemy, which door did I touch".

Step 5: touch and mouse, with pointer events

Pointer events cover the mouse, a finger and a stylus with one set of events, so there is no need to write the touch code and the mouse code twice. The jump button is drawn on the canvas; a touch that starts on it is a jump, and a touch anywhere else may become a swipe.

const JUMP_BUTTON = { x: VIEW_W - 44, y: VIEW_H - 44, r: 30 };
const touches = new Map();   // pointerId -> what that finger is doing


canvas.addEventListener('pointerdown', (e) => {
  canvas.setPointerCapture(e.pointerId);
  const p = toWorld(e);
  // A bit bigger than it looks: a thumb is not a mouse pointer.
  const hitButton = Math.hypot(p.x - JUMP_BUTTON.x, p.y - JUMP_BUTTON.y) <= JUMP_BUTTON.r * 1.4;
  if (hitButton) pressJump();
  touches.set(e.pointerId, { jump: hitButton, startX: e.clientX, startY: e.clientY, swiped: false });
});

canvas.addEventListener('pointermove', (e) => {
  const t = touches.get(e.pointerId);
  if (!t || t.jump || t.swiped) return;
  const dx = e.clientX - t.startX;
  const dy = e.clientY - t.startY;
  // Mostly sideways and far enough: a swipe. One per touch.
  if (Math.abs(dx) >= SWIPE && Math.abs(dx) > Math.abs(dy)) {
    face(dx > 0 ? 1 : -1);
    t.swiped = true;
  }
});

function endTouch(e) {
  const t = touches.get(e.pointerId);
  if (t && t.jump) releaseJump();
  touches.delete(e.pointerId);
}
canvas.addEventListener('pointerup', endTouch);
canvas.addEventListener('pointercancel', endTouch);

A few decisions worth a line each:

  • The Map of touches. On a phone you jump with one thumb while the other one swipes. Each finger has its own pointerId, so each one keeps its own story: a finger that started on the button stays a jump until it lifts, even if it slides off.
  • setPointerCapture keeps sending us the events of that finger even when it leaves the canvas. Without it, a finger that lifts outside the canvas would leave the jump held forever.
  • A generous button. It accepts touches up to 1.4 times its radius. A fingertip is much bigger than a mouse pointer, and a button that ignores a touch just next to it feels broken.
  • The swipe is measured in screen pixels, not world units: what matters is how far the finger moved, whatever the size of the game. It also has to be more sideways than vertical, and it counts once per touch.

Step 6: the jump

Here is the new update(). It looks longer than a jump needs, because it does three things at once: the jump, its variable height, and the two tricks of the next section.

const player = {
  // ...
  coyote: 0,   // time left to jump without ground
  buffer: 0,   // time left on a remembered jump
};

function update(dt) {
  if (input.jumpPressed) {
    player.buffer = BUFFER;
    input.jumpPressed = false;
  }
  player.buffer -= dt;
  player.coyote = player.onGround ? COYOTE : player.coyote - dt;

  // The jump happens when both timers are running at once.
  if (player.buffer > 0 && player.coyote > 0) {
    player.vy = -JUMP_SPEED;
    player.buffer = 0;
    player.coyote = 0;
  }

  // Let go while rising, and the rest of the jump is cut short.
  if (!input.jumpHeld && player.vy < -JUMP_CUT) player.vy = -JUMP_CUT;

  moveX(dt);
  moveY(dt);
}

The jump itself is one line: player.vy = -JUMP_SPEED. Negative, because y grows downward. From there gravity does the rest, the same gravity from part 2, which slows the rise until Cubi falls back down. The ceiling collision we wrote in part 2 finally gets used: jump under a block and Cubi bumps his head.

The last line is the variable jump height: if you let go of the button while Cubi is still rising fast, his upward speed is cut to JUMP_CUT. A tap gives a short hop and a long press gives the full jump. It is the difference between a jump you trigger and a jump you control, and players notice it without being able to name it.

Step 7: coyote time and jump buffer

Notice that a press does not jump by itself, and being on the ground does not allow a jump by itself either. Each one starts a small timer, and the jump happens when both are running at the same time. That gives us two tricks that almost every good platformer uses:

  • Coyote time (named after the cartoon coyote who runs off a cliff and only falls when he notices): for 80 milliseconds after walking off a ledge you can still jump. Without it, the jump you pressed a hair too late is lost, and it feels like the game ignored you.
  • Jump buffer: a press made up to 100 milliseconds before landing is remembered and happens on landing. Without it, pressing just before touching the ground does nothing, and that also feels like the game ignored you.

Neither of them is visible, and nobody will thank you for them. But without them the controls feel stiff, and that is something players notice right away.

Step 8: drawing the button

function drawJumpButton() {
  const b = JUMP_BUTTON;
  // Darker while held: the thumb gets an answer.
  ctx.fillStyle = input.jumpHeld ? 'rgba(0, 0, 0, .55)' : 'rgba(0, 0, 0, .3)';
  ctx.beginPath();
  ctx.arc(b.x, b.y, b.r, 0, Math.PI * 2);
  ctx.fill();
  ctx.strokeStyle = 'rgba(255, 255, 255, .85)';
  ctx.lineWidth = 2;
  ctx.stroke();
  // An arrow and no word: it works in every language.
  ctx.fillStyle = '#fff';
  ctx.beginPath();
  ctx.moveTo(b.x, b.y - 12);
  ctx.lineTo(b.x + 11, b.y + 6);
  ctx.lineTo(b.x - 11, b.y + 6);
  ctx.closePath();
  ctx.fill();
}

The button is drawn on the canvas instead of being an HTML element, so it grows and shrinks with the game and always sits in the same corner of the world. It gets darker while it is pressed: on a touch screen there is no click to feel, and that change of color is the only answer the thumb gets. Later in the series this same button will change its symbol when Cubi stands in front of a door, and open it.

Try it

On a phone, the round button jumps and a swipe left or right turns Cubi around. On a computer, the space bar, the up arrow or W jump, and the arrows or A and D choose the direction. Try a short tap and a long press, and climb the hill step by step.

The level of this part has changed: everything now stands on the ground, and there is nothing floating. That is on purpose. Cubi never stops, so a block one tile above his head turns every jump under it into a bump, and the side of a floating platform turns him around: the jump only works with perfect timing, and that feels broken, not difficult. For the same reason no gap is exactly one tile wide, or Cubi would bounce in it on every step. Designing for a character who always runs has its own rules, and we will collect them when we build real levels in part 4.

Download the code of part 3

The file is the complete game up to this point, with its comments in English, Spanish and Portuguese. Try setting COYOTE and BUFFER to 0 and jumping off the edges: the difference is small on paper and very clear in your hands.

Next Monday: the level and the camera

A single screen is not much of a level. In part 4 the map gets written as text, much easier to design, it gets wider than the screen, and a camera follows Cubi while looking ahead in the direction he runs. Meanwhile, you can play the games we make at Raptware on our games page.

Which control did you like best: the button, the swipe or the keyboard? Tell us in the comments.

← All posts

Comments

We read every comment before publishing it. Please be kind, and don't share personal details.