TExcelTAD
Home › 2D Games with JavaScript & Canvas › Platformer 2: Tilemaps & Tile Collision

Platformer 2: Tilemaps & Tile Collision

A flat floor isn't a level. Real platformer levels are built from tiles: a grid of small squares (here 16×16 pixels), each either empty or solid. The level itself is just data, and the simplest data format is the one you can edit by hand: an array of strings, one string per row, one character per tile.

js
const T = 16;               // tile size in pixels
const MAP = [
  '##########',
  '#........#',
  '#...##...#',
  '#........#',
  '##########',
];

MAP[row][col] gives one tile. Row is y, column is x, so it's MAP[ty][tx], which is the opposite order from (x, y) and a very common source of bugs.

From pixels to tiles and back

Question Formula
Which tile column holds pixel x? tx = Math.floor(x / T)
Which tile row holds pixel y? ty = Math.floor(y / T)
Where does tile (tx, ty) start? x = tx * T, y = ty * T
Level size in pixels MAP[0].length * T by MAP.length * T

The beauty of tiles: to know whether a box touches a wall you don't test it against every wall in the level. You compute which tiles the box overlaps (at most a handful) and look only at those.

AABB vs tiles, one axis at a time

The player is an axis-aligned bounding box (AABB). Moving it diagonally into a corner raises a question: did it hit the wall or the floor? The standard answer is to not move diagonally at all: move along x and fix any overlap by pushing back along x, then move along y and fix any overlap along y. Each axis then has an unambiguous answer, and you know exactly which side was hit.

js · try it yourself
const T = 16;
const MAP = [
  '#......#',
  '#......#',
  '#...##.#',
  '#......#',
  '########',
];
const EPS = 0.001;   // the right/bottom edge belongs to the next tile only if we're past it

function solidAt(tx, ty) {
  if (ty < 0 || ty >= MAP.length || tx < 0 || tx >= MAP[0].length) return true;   // outside = wall
  return MAP[ty][tx] === '#';
}

function moveX(b, dx) {
  b.x += dx;
  const top = Math.floor(b.y / T), bottom = Math.floor((b.y + b.h - EPS) / T);
  if (dx > 0) {
    const tx = Math.floor((b.x + b.w - EPS) / T);
    for (let ty = top; ty <= bottom; ty++) if (solidAt(tx, ty)) { b.x = tx * T - b.w; return 'right'; }
  } else if (dx < 0) {
    const tx = Math.floor(b.x / T);
    for (let ty = top; ty <= bottom; ty++) if (solidAt(tx, ty)) { b.x = (tx + 1) * T; return 'left'; }
  }
  return null;
}

function moveY(b, dy) {
  b.y += dy;
  const left = Math.floor(b.x / T), right = Math.floor((b.x + b.w - EPS) / T);
  if (dy > 0) {
    const ty = Math.floor((b.y + b.h - EPS) / T);
    for (let tx = left; tx <= right; tx++) if (solidAt(tx, ty)) { b.y = ty * T - b.h; return 'floor'; }
  } else if (dy < 0) {
    const ty = Math.floor(b.y / T);
    for (let tx = left; tx <= right; tx++) if (solidAt(tx, ty)) { b.y = (ty + 1) * T; return 'ceiling'; }
  }
  return null;
}

console.log('pixel (70, 40) is in tile', [Math.floor(70 / T), Math.floor(40 / T)], 'solid:', solidAt(4, 2));

const a = { x: 20, y: 10, w: 12, h: 16 };
console.log('fall 50px:', moveY(a, 50), a);

const b = { x: 40, y: 36, w: 12, h: 16 };
console.log('run right 20px:', moveX(b, 20), b);

const fast = { x: 40, y: 36, w: 12, h: 16 };
console.log('run right 30px in ONE step:', moveX(fast, 30), fast);

const c = { x: 70, y: 10, w: 12, h: 16 };          // just above the ## block
const hitX = moveX(c, 4), hitY = moveY(c, 12);
console.log('diagonal (4, 12):', hitX, hitY, c);
pixel (70, 40) is in tile [ 4, 2 ] solid: true
fall 50px: floor { x: 20, y: 48, w: 12, h: 16 }
run right 20px: right { x: 52, y: 36, w: 12, h: 16 }
run right 30px in ONE step: right { x: 68, y: 36, w: 12, h: 16 }
diagonal (4, 12): null floor { x: 74, y: 16, w: 12, h: 16 }

Read the results:

  • Fall stops with the feet exactly on top of the bottom row (y = 64 - 16 = 48), and reports 'floor', which is the ground check.
  • Run right stops flush against the left side of the ## block (x = 64 - 12 = 52). The box spans rows 2 and 3, so both were checked.
  • Run right 30px in one step is a bug on purpose: the leading edge jumps from column 3 straight into column 5, moveX only looks at column 5, and the box ends up at x = 68, inside the block. See the note below.
  • Diagonal: moving x first finds nothing (the box is still above the block), then moving y lands it on top of the block. Done the other way around, or both at once, the box could snag on the block's corner.

Note: All of this assumes a box never moves more than one tile in a single step. Otherwise it can jump straight over a thin wall ("tunneling"). At 60 updates per second with 16-pixel tiles, that means less than 960 px/s. The game caps falling speed at 600 px/s, so it's safe. For faster objects, split the move into smaller sub-steps.

Step 2: a tile level

The game now has a 30×17 tile level drawn from MAP. The player uses moveX and moveY from above, and moveY returning 'floor' is the new ground check. Hitting a ceiling stops the upward velocity.

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 T = 16;
const MAP = [
  '##############################',
  '#............................#',
  '#............................#',
  '#............................#',
  '#.......####.................#',
  '#............................#',
  '#............................#',
  '#..............#####.........#',
  '#............................#',
  '#............................#',
  '#....#####...........####....#',
  '#............................#',
  '#............................#',
  '#..........####..........##..#',
  '#..........................###',
  '#.....##.............#.....###',
  '##############################',
];
const GRAVITY = 1500, JUMP_SPEED = 440, CUT = 0.45, MAX_FALL = 600;
const RUN_SPEED = 150, ACCEL = 1400, FRICTION = 1800, EPS = 0.001;
const player = { x: 40, y: 200, w: 12, h: 16, vx: 0, vy: 0, onGround: false, facing: 1 };
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 solidAt(tx, ty) {
  if (ty < 0 || ty >= MAP.length || tx < 0 || tx >= MAP[0].length) return true;
  return MAP[ty][tx] === '#';
}
function moveX(b, dx) {
  b.x += dx;
  const top = Math.floor(b.y / T), bottom = Math.floor((b.y + b.h - EPS) / T);
  if (dx > 0) {
    const tx = Math.floor((b.x + b.w - EPS) / T);
    for (let ty = top; ty <= bottom; ty++) if (solidAt(tx, ty)) { b.x = tx * T - b.w; return 'right'; }
  } else if (dx < 0) {
    const tx = Math.floor(b.x / T);
    for (let ty = top; ty <= bottom; ty++) if (solidAt(tx, ty)) { b.x = (tx + 1) * T; return 'left'; }
  }
  return null;
}
function moveY(b, dy) {
  b.y += dy;
  const left = Math.floor(b.x / T), right = Math.floor((b.x + b.w - EPS) / T);
  if (dy > 0) {
    const ty = Math.floor((b.y + b.h - EPS) / T);
    for (let tx = left; tx <= right; tx++) if (solidAt(tx, ty)) { b.y = ty * T - b.h; return 'floor'; }
  } else if (dy < 0) {
    const ty = Math.floor(b.y / T);
    for (let tx = left; tx <= right; tx++) if (solidAt(tx, ty)) { b.y = (ty + 1) * T; return 'ceiling'; }
  }
  return null;
}

function update(dt) {
  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);

  if (jumpPressed() && player.onGround) player.vy = -JUMP_SPEED;
  const held = jumpHeld();
  if (jumpWasHeld && !held && player.vy < 0) player.vy *= CUT;
  jumpWasHeld = held;
  player.vy = Math.min(player.vy + GRAVITY * dt, MAX_FALL);

  if (moveX(player, player.vx * dt)) player.vx = 0;          // x first...
  const hit = moveY(player, player.vy * dt);                  // ...then y
  player.onGround = hit === 'floor';
  if (hit) player.vy = 0;
}

function drawTiles() {
  for (let ty = 0; ty < MAP.length; ty++) {
    for (let tx = 0; tx < MAP[ty].length; tx++) {
      if (MAP[ty][tx] !== '#') continue;
      const x = tx * T, y = ty * T;
      ctx.fillStyle = '#5b3a29'; ctx.fillRect(x, y, T, T);
      ctx.fillStyle = '#6d4a36'; ctx.fillRect(x + 2, y + 2, T - 4, T - 4);   // bevel
      if (ty > 0 && MAP[ty - 1][tx] !== '#') { ctx.fillStyle = '#4caf50'; ctx.fillRect(x, y, T, 3); }   // grass on top
    }
  }
}

function drawPlayer() {
  const x = Math.round(player.x), y = Math.round(player.y);
  ctx.fillStyle = '#ffb74d'; ctx.fillRect(x, y, player.w, player.h);
  ctx.fillStyle = '#5d4037'; ctx.fillRect(x, y, player.w, 4);
  ctx.fillStyle = '#fff';
  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);
  drawTiles();
  drawPlayer();
  if (keys.has('KeyG')) {                                        // hold G: show the tiles the player overlaps
    ctx.strokeStyle = '#ff0';
    const l = Math.floor(player.x / T), r = Math.floor((player.x + player.w - EPS) / T);
    const t = Math.floor(player.y / T), b = Math.floor((player.y + player.h - EPS) / T);
    for (let ty = t; ty <= b; ty++) for (let tx = l; tx <= r; tx++) ctx.strokeRect(tx * T + 0.5, ty * T + 0.5, T - 1, T - 1);
  }
}

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

The update now reads almost like a description of the rules: compute velocities, move x and stop on a wall, move y and stop on a floor or ceiling, and whatever moveY hit decides onGround. Hold G to see which tiles the player overlaps: at most 2×3 tiles are ever checked, however big the level gets.

Try editing the level: change a few . into # and press Run. Making levels is now as easy as typing.

Tip: Drawing every tile every frame is fine for a screen-sized map (510 tiles). For big maps, either draw only the tiles inside the camera (next lessons), or draw the static tiles once onto an offscreen canvas and copy that single image each frame with drawImage.

Test yourself

A tile map is stored as an array of strings MAP. How do you read the tile at column tx, row ty?

  1. MAP[tx][ty]
  2. MAP[ty][tx]
  3. MAP[tx * ty]
  4. MAP.get(tx, ty)

Why resolve collisions one axis at a time (x, then y)?

  1. It's the only way canvas can draw
  2. Each axis then has an unambiguous push-back direction, so corners don't snag and you know which side was hit
  3. It makes the player jump higher
  4. It avoids floating-point numbers

Which tile column contains pixel x = 47 with 16-pixel tiles?

  1. 2
  2. 3
  3. 47
  4. 0