Platformer 5: Hazards, Checkpoints & Goal
The platformer has movement, collision and a camera, but no way to fail and no way to win. This last step turns the playground into a level: spikes and pits kill, checkpoint flags decide where you come back, and a goal flag ends the level with a results screen. All three are new tile characters in the map, so designing the level stays a matter of editing text.
| Character | Meaning |
|---|---|
# |
solid ground |
P |
player start (first respawn point) |
^ |
spikes: touching them kills |
C |
checkpoint flag: touching it moves your respawn point here |
G |
goal flag: touching it wins the level |
Fair hitboxes for hazards
Spikes fill the bottom half of a tile at most, and their tips are thin. If the whole 16×16 tile killed the player, you'd die standing next to a spike or jumping cleanly over it, and the game would feel unfair. Use a smaller hitbox than the drawing: here the bottom 8 pixels, inset 3 pixels on each side. The general rule in action games: hazard hitboxes slightly smaller than they look, pickup hitboxes slightly larger.
const T = 16;
const overlaps = (a, b) => a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
const spikeBox = (tx, ty) => ({ x: tx * T + 3, y: ty * T + 8, w: T - 6, h: 8 });
const tileBox = (tx, ty) => ({ x: tx * T, y: ty * T, w: T, h: T });
// A spike at tile (5, 3): pixels x 80-95, y 48-63. The player is 12x16.
const cases = {
'brushing its left side': { x: 69, y: 48, w: 12, h: 16 },
'jumping just over the tips': { x: 82, y: 38, w: 12, h: 16 },
'landing on it': { x: 82, y: 46, w: 12, h: 16 },
};
for (const [name, p] of Object.entries(cases)) {
console.log(name.padEnd(27), 'tile box:', overlaps(p, tileBox(5, 3)) ? 'DEAD' : 'safe', ' spike box:', overlaps(p, spikeBox(5, 3)) ? 'DEAD' : 'safe');
}brushing its left side tile box: DEAD spike box: safe
jumping just over the tips tile box: DEAD spike box: safe
landing on it tile box: DEAD spike box: DEAD
With the full tile box, brushing the spike from the side or clearing it by two pixels is a death. With the spike box, only actually touching the spikes counts.
Checkpoints and respawning
A checkpoint is just a remembered position. Death puts the player back at respawn with zero velocity. Touching a checkpoint flag updates respawn, but only if it's further along than the current one, so walking back past an old flag doesn't move your respawn point backwards. Here's the logic stripped down to a one-dimensional walk through a level:
const LEVEL = 'P...^..C...^^..C....^...G'; // one tile per character
let respawn = 0, deaths = 0;
const log = [];
function enter(x) {
const tile = LEVEL[x];
if (tile === 'C' && x > respawn) { respawn = x; log.push(`checkpoint at ${x}`); }
if (tile === '^') { deaths++; log.push(`spikes at ${x}, respawn at ${respawn}`); return respawn; }
if (tile === 'G') { log.push(`goal reached, ${deaths} deaths`); return -1; }
return x;
}
// The player walks right, dies on each spike the first time, and jumps over it from then on.
const jumpedOnce = new Set();
let x = 0;
while (x >= 0 && x < LEVEL.length - 1) {
let next = x + 1;
while (LEVEL[next] === '^' && jumpedOnce.has(next)) next++; // learned to jump these
if (LEVEL[next] === '^') jumpedOnce.add(next);
x = enter(next);
}
log.forEach((line) => console.log(line));spikes at 4, respawn at 0
checkpoint at 7
spikes at 11, respawn at 7
spikes at 12, respawn at 7
checkpoint at 15
spikes at 20, respawn at 15
goal reached, 4 deaths
The first spike sends the player back to the start because no checkpoint was reached yet; after that, every death costs only the stretch since the last flag. Placing checkpoints is a design decision: just before a hard section, never right after one.
Note: Respawning should reset the player's state, not only the position: velocity to zero, coyote and buffer timers cleared, and (in bigger games) temporary power-ups removed. Leftover velocity is a classic bug: you respawn and immediately slide back into the pit.
Step 5: the complete level
Reach the goal flag at the far right. Spikes and pits kill you; the two checkpoint flags turn green when you touch them. Your time and deaths are shown at the end. R restarts the level from the beginning.
<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 = [
'#........................................................................................#',
'#........................................................................................#',
'#........................................................................................#',
'#........................................................................................#',
'#........................................................................................#',
'#........................................................................................#',
'#........................................................................................#',
'#........................................................................................#',
'#........................................................................................#',
'#.......................####.............................................................#',
'#........................................................................................#',
'#........................................................................................#',
'#.................####........####.......................####............................#',
'#........................................................................................#',
'#........................................................................................#',
'#............####.....................####...........###....................####.........#',
'#........................................................................................#',
'#........................####.................................###........................#',
'#.......####.....................####...........####...................####.......###....#',
'#.............#..........................................................................#',
'#..P..........#...............^^.....C..................C..^^..................^......G..#',
'####################....####################....##################....####################',
];
const COLS = MAP[0].length, ROWS = MAP.length, LEVEL_W = COLS * T, LEVEL_H = ROWS * T;
const GRAVITY = 1500, JUMP_SPEED = 440, CUT = 0.45, MAX_FALL = 600;
const RUN_SPEED = 150, ACCEL = 1400, FRICTION = 1800, EPS = 0.001;
const COYOTE_TIME = 0.1, BUFFER_TIME = 0.12;
const DEAD_W = 40, DEAD_H = 40, CAM_SPEED = 6;
// read the special tiles out of the map once
const spikes = [], flags = [];
let start = null, goal = null;
MAP.forEach((row, ty) => [...row].forEach((ch, tx) => {
if (ch === '^') spikes.push({ x: tx * T + 3, y: ty * T + 8, w: T - 6, h: 8 });
if (ch === 'C') flags.push({ x: tx * T + 2, y: ty * T, w: 12, h: T, reached: false });
if (ch === 'P') start = { x: tx * T + 2, y: ty * T };
if (ch === 'G') goal = { x: tx * T, y: ty * T - T, w: T, h: 2 * T };
}));
const player = { x: 0, y: 0, w: 12, h: 16, vx: 0, vy: 0, onGround: false, facing: 1 };
const cam = { x: 0, y: 0, tx: 0, ty: 0 };
let jumpWasHeld, coyote, buffer, respawn, deaths, time, state, deadTimer;
function respawnPlayer() {
Object.assign(player, { x: respawn.x, y: respawn.y, vx: 0, vy: 0, onGround: false, facing: 1 });
coyote = 0; buffer = 0; jumpWasHeld = false;
}
function resetLevel() {
for (const f of flags) f.reached = false;
respawn = { ...start };
deaths = 0; time = 0; state = 'play'; deadTimer = 0;
respawnPlayer();
cam.x = cam.tx = clamp(player.x - W / 2, 0, LEVEL_W - W);
cam.y = cam.ty = clamp(player.y - H / 2, 0, LEVEL_H - H);
}
const approach = (v, t, s) => (v < t ? Math.min(v + s, t) : Math.max(v - s, t));
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
const overlaps = (a, b) => a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
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 (tx < 0 || tx >= COLS) return true;
if (ty < 0 || ty >= ROWS) return false;
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 updateCamera(dt) {
const fx = player.x + player.w / 2 - W / 2, fy = player.y + player.h / 2 - H / 2;
if (fx > cam.tx + DEAD_W / 2) cam.tx = fx - DEAD_W / 2;
if (fx < cam.tx - DEAD_W / 2) cam.tx = fx + DEAD_W / 2;
if (fy > cam.ty + DEAD_H / 2) cam.ty = fy - DEAD_H / 2;
if (fy < cam.ty - DEAD_H / 2) cam.ty = fy + DEAD_H / 2;
cam.tx = clamp(cam.tx, 0, LEVEL_W - W);
cam.ty = clamp(cam.ty, 0, LEVEL_H - H);
const k = 1 - Math.exp(-CAM_SPEED * dt);
cam.x += (cam.tx - cam.x) * k;
cam.y += (cam.ty - cam.y) * k;
}
function die() {
deaths++;
state = 'dead';
deadTimer = 0.6; // a short pause so the death registers
}
function update(dt) {
if (pressed.has('KeyR')) { resetLevel(); return; }
if (state === 'won') return;
if (state === 'dead') {
deadTimer -= dt;
if (deadTimer <= 0) { respawnPlayer(); state = 'play'; }
updateCamera(dt);
return;
}
time += 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 (player.onGround) coyote = COYOTE_TIME; else coyote -= dt;
if (jumpPressed()) buffer = BUFFER_TIME; else buffer -= dt;
if (buffer > 0 && coyote > 0) { player.vy = -JUMP_SPEED; buffer = 0; coyote = 0; }
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;
const hit = moveY(player, player.vy * dt);
player.onGround = hit === 'floor';
if (hit) player.vy = 0;
// hazards, checkpoints, goal
if (player.y > LEVEL_H + 40 || spikes.some((s) => overlaps(player, s))) die();
for (const f of flags) {
if (!f.reached && overlaps(player, f) && f.x > respawn.x) {
f.reached = true;
respawn = { x: f.x, y: f.y };
}
}
if (overlaps(player, goal)) state = 'won';
updateCamera(dt);
}
function drawBackground(camX) {
const sky = ctx.createLinearGradient(0, 0, 0, H);
sky.addColorStop(0, '#1a237e'); sky.addColorStop(1, '#5c6bc0');
ctx.fillStyle = sky; ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#3949ab';
const off = Math.round(camX / 3) % 160;
for (let i = -1; i < 5; i++) {
const x = i * 160 - off;
ctx.beginPath(); ctx.moveTo(x, H); ctx.lineTo(x + 80, 150); ctx.lineTo(x + 160, H); ctx.fill();
}
}
function drawTiles() {
const c0 = Math.max(0, Math.floor(cam.x / T)), c1 = Math.min(COLS - 1, Math.floor((cam.x + W) / T));
const r0 = Math.max(0, Math.floor(cam.y / T)), r1 = Math.min(ROWS - 1, Math.floor((cam.y + H) / T));
for (let ty = r0; ty <= r1; ty++) {
for (let tx = c0; tx <= c1; tx++) {
const ch = MAP[ty][tx], x = tx * T, y = ty * T;
if (ch === '#') {
ctx.fillStyle = '#5b3a29'; ctx.fillRect(x, y, T, T);
ctx.fillStyle = '#6d4a36'; ctx.fillRect(x + 2, y + 2, T - 4, T - 4);
if (ty > 0 && MAP[ty - 1][tx] !== '#') { ctx.fillStyle = '#4caf50'; ctx.fillRect(x, y, T, 3); }
} else if (ch === '^') {
ctx.fillStyle = '#cfd8dc'; // three spikes drawn as triangles
for (let i = 0; i < 3; i++) {
ctx.beginPath(); ctx.moveTo(x + i * 5 + 1, y + T); ctx.lineTo(x + i * 5 + 3.5, y + 7); ctx.lineTo(x + i * 5 + 6, y + T); ctx.fill();
}
}
}
}
}
function drawFlag(x, y, color, tall) {
ctx.fillStyle = '#eceff1'; ctx.fillRect(x, y - (tall ? T : 0), 2, tall ? 2 * T : T);
ctx.fillStyle = color;
ctx.beginPath(); ctx.moveTo(x + 2, y - (tall ? T : 0)); ctx.lineTo(x + 13, y + 4 - (tall ? T : 0)); ctx.lineTo(x + 2, y + 8 - (tall ? T : 0)); ctx.fill();
}
function drawPlayer() {
const x = Math.round(player.x), y = Math.round(player.y);
if (state === 'dead') { // flash while dead
if (Math.floor(deadTimer * 20) % 2 === 0) { ctx.fillStyle = '#ff5252'; ctx.fillRect(x, y, player.w, player.h); }
return;
}
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() {
const camX = Math.round(cam.x), camY = Math.round(cam.y);
drawBackground(camX);
ctx.save();
ctx.translate(-camX, -camY);
drawTiles();
for (const f of flags) drawFlag(f.x, f.y, f.reached ? '#66bb6a' : '#ef5350', false);
drawFlag(goal.x + 6, goal.y + T, '#ffd54f', true);
drawPlayer();
ctx.restore();
ctx.fillStyle = '#e8eaf6'; ctx.font = '12px system-ui, sans-serif'; ctx.textAlign = 'left';
ctx.fillText(`time ${time.toFixed(1)}s deaths ${deaths} checkpoints ${flags.filter((f) => f.reached).length}/${flags.length}`, 8, 16);
if (state === 'won') banner('Level complete!', `${time.toFixed(1)} s, ${deaths} ${deaths === 1 ? 'death' : 'deaths'} - press R to play again`);
}
resetLevel();
run(update, draw, 'Arrows / A D to run, Space / W / Up to jump, R to restart');
</script>How the step fits together:
- Special tiles are read once. At startup the map is scanned and every
^,C,PandGbecomes an object with a hitbox. The tile map itself stays the source of truth for solid ground. - The game has states:
'play','dead'(a 0.6 s pause with a flashing player, so the death is readable) and'won'.updatechecks the state first and only runs the parts that apply, the same pattern as Pong's game states. resetLevel()vsrespawnPlayer(). Respawning resets the player; resetting the level also clears flags, deaths and time. Keeping the two separate makes it obvious what each one touches.- The goal freezes the update and shows a banner with the results.
That's a complete, small platformer: about 270 lines including the play kit, no libraries. The Polish section adds particles, screen shake and sound to games like this one.
Tip: Playtest your own level by watching someone else play it without helping. Where they die repeatedly, add a checkpoint or move a spike; where they never hesitate, you can make it harder.
Test yourself
Why is the spike hitbox smaller than its 16×16 tile?
- To save memory
- So brushing past or narrowly clearing the spikes doesn't kill, which feels fair
- Canvas can't draw full tiles
- To make the level harder
A player touches an older checkpoint after reaching a later one. What should happen?
- The respawn point moves back to the older flag
- Nothing: the respawn point only moves forward
- The level restarts
- The player dies
What must respawning reset besides the player's position?
- Nothing else
- Velocity and input timers such as coyote time and the jump buffer
- The camera's level size
- The tile map