Shooter 1: Movement & Aiming
Project 3 is a top-down shooter, sometimes called a "twin-stick" game: one hand moves the ship with the keyboard, the other hand aims with the mouse. Over four lessons you'll add projectiles, enemies, health and finally object pooling. This first step gets the two most important feelings right: moving in eight directions at a constant speed, and aiming exactly where the mouse points.
| Step | Lesson | New ideas |
|---|---|---|
| 1 | Movement & Aiming | input vector, normalizing diagonals, atan2, mouse to canvas coordinates |
| 2 | Projectiles & Cooldowns | bullets with velocity and lifetime, fire rate |
| 3 | Enemies, Spawning & Health | spawn timers, difficulty ramp, damage, invulnerability |
| 4 | Object Pooling | reusing objects instead of allocating, measuring it |
The input vector
Instead of moving the player directly inside each if, collect the keys into an input vector (dx, dy): -1, 0 or 1 on each axis. Then move once, using that vector.
let dx = 0, dy = 0;
if (keys.has('KeyA') || keys.has('ArrowLeft')) dx -= 1;
if (keys.has('KeyD') || keys.has('ArrowRight')) dx += 1;
if (keys.has('KeyW') || keys.has('ArrowUp')) dy -= 1;
if (keys.has('KeyS') || keys.has('ArrowDown')) dy += 1;Pressing left and right together gives dx = 0, so opposite keys cancel out naturally, with no special case.
Why diagonals are too fast
If you hold W and D, the vector is (1, -1). Its length is √2 ≈ 1.414, so the player moves 41% faster diagonally than straight. Players notice this right away. The fix is to normalize the vector, dividing it by its length so it always has length 1 (or 0 when no key is held):
function normalize(dx, dy) {
const len = Math.hypot(dx, dy); // √(dx² + dy²)
return len === 0 ? [0, 0] : [dx / len, dy / len];
}
const speed = 140; // pixels per second
for (const [dx, dy] of [[1, 0], [1, -1], [0, 0]]) {
const raw = Math.hypot(dx, dy) * speed;
const [nx, ny] = normalize(dx, dy);
const fixed = Math.hypot(nx, ny) * speed;
console.log(`input (${dx}, ${dy}): raw ${raw.toFixed(1)} px/s, normalized ${fixed.toFixed(1)} px/s`);
}input (1, 0): raw 140.0 px/s, normalized 140.0 px/s
input (1, -1): raw 198.0 px/s, normalized 140.0 px/s
input (0, 0): raw 0.0 px/s, normalized 0.0 px/s
Tip: On a gamepad the stick already gives a vector with a length between 0 and 1, so a half-pushed stick should move at half speed. Only normalize when the length is greater than 1 (see Gamepad Input).
Aiming with atan2
To point the gun at the mouse, you need the angle of the vector from the player to the mouse. Math.atan2(y, x) returns exactly that, in radians, from −π to π. Note the order: y first.
function aimAngle(px, py, mx, my) {
return Math.atan2(my - py, mx - px);
}
const deg = (rad) => Math.round(rad * 180 / Math.PI);
const player = { x: 240, y: 135 };
const targets = { right: [340, 135], below: [240, 200], left: [100, 135], above: [240, 20], 'up-right': [300, 75] };
for (const [name, [mx, my]] of Object.entries(targets)) {
console.log(name.padEnd(8), deg(aimAngle(player.x, player.y, mx, my)), 'degrees');
}right 0 degrees
below 90 degrees
left 180 degrees
above -90 degrees
up-right -45 degrees
Because the canvas y axis points down, "below" is +90° and "above" is −90°. That's exactly what ctx.rotate() expects, so you can pass the angle straight to it: draw the ship pointing right (angle 0) and rotate the whole drawing.
Mouse position in canvas coordinates
The canvas has 480×270 pixels of drawing space, but CSS scales it to fit the frame. A mouse event gives positions in CSS pixels relative to the page, so convert them: subtract the canvas's on-screen corner, then scale by the ratio of drawing size to displayed size.
cv.addEventListener('pointermove', (e) => {
const r = cv.getBoundingClientRect();
mouse.x = (e.clientX - r.left) * W / r.width;
mouse.y = (e.clientY - r.top) * H / r.height;
});Without the W / r.width factor, aiming is only correct when the canvas happens to be displayed at exactly 480 pixels wide. Drag the frame's corner to resize it and the crosshair still lines up.
Step 1: a ship that moves and aims
Click the game, then move with WASD (or the arrow keys) and aim with the mouse. The ship is drawn with paths, translated to its position and rotated by the aim angle.
<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 player = { x: W / 2, y: H / 2, r: 11, speed: 140, angle: 0 };
const mouse = { x: W / 2 + 80, y: H / 2 };
cv.addEventListener('pointermove', (e) => {
const r = cv.getBoundingClientRect();
mouse.x = (e.clientX - r.left) * W / r.width;
mouse.y = (e.clientY - r.top) * H / r.height;
});
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
function update(dt) {
let dx = 0, dy = 0;
if (keys.has('KeyA') || keys.has('ArrowLeft')) dx -= 1;
if (keys.has('KeyD') || keys.has('ArrowRight')) dx += 1;
if (keys.has('KeyW') || keys.has('ArrowUp')) dy -= 1;
if (keys.has('KeyS') || keys.has('ArrowDown')) dy += 1;
const len = Math.hypot(dx, dy);
if (len > 0) { dx /= len; dy /= len; } // same speed in all 8 directions
player.x = clamp(player.x + dx * player.speed * dt, player.r, W - player.r);
player.y = clamp(player.y + dy * player.speed * dt, player.r, H - player.r);
player.angle = Math.atan2(mouse.y - player.y, mouse.x - player.x);
}
function drawShip(x, y, angle) {
ctx.save();
ctx.translate(Math.round(x), Math.round(y));
ctx.rotate(angle); // the ship is drawn facing right (angle 0)
ctx.fillStyle = '#4dd0e1';
ctx.beginPath();
ctx.moveTo(14, 0); ctx.lineTo(-9, -9); ctx.lineTo(-5, 0); ctx.lineTo(-9, 9);
ctx.closePath();
ctx.fill();
ctx.fillStyle = '#e0f7fa';
ctx.fillRect(2, -2, 10, 4); // the gun barrel
ctx.restore();
}
function draw() {
ctx.fillStyle = '#0e1018'; ctx.fillRect(0, 0, W, H);
ctx.strokeStyle = '#1b2030'; // a grid makes movement easy to see
for (let x = 0; x <= W; x += 30) { ctx.beginPath(); ctx.moveTo(x + 0.5, 0); ctx.lineTo(x + 0.5, H); ctx.stroke(); }
for (let y = 0; y <= H; y += 30) { ctx.beginPath(); ctx.moveTo(0, y + 0.5); ctx.lineTo(W, y + 0.5); ctx.stroke(); }
drawShip(player.x, player.y, player.angle);
ctx.strokeStyle = '#ff5252'; // crosshair
const mx = Math.round(mouse.x), my = Math.round(mouse.y);
ctx.beginPath(); ctx.arc(mx, my, 6, 0, Math.PI * 2);
ctx.moveTo(mx - 10, my); ctx.lineTo(mx + 10, my);
ctx.moveTo(mx, my - 10); ctx.lineTo(mx, my + 10);
ctx.stroke();
}
run(update, draw, 'WASD / arrows to move, mouse to aim');
</script>What's new compared with the kit's demo square:
- One movement path. Keys build the vector, the vector is normalized, and position changes by
direction × speed × dt. Changingspeedchanges the feel everywhere at once. clampkeeps the ship's whole circle on screen, not just its center.save/translate/rotate/restore. The ship's shape is described around(0, 0)facing right; the transform moves and turns it.restore()undoes the transform so the crosshair and grid are drawn normally.Math.roundon the translation keeps the ship's edges crisp instead of blurring between pixels.
Note: The aim angle is computed in
update, not in the mouse handler. The mouse might not move while the ship does, and the angle must follow the ship too.
Test yourself
Holding W and D gives the input vector (1, -1). Why do we normalize it?
- To make it point up
- Its length is about 1.414, so without normalizing the player moves about 41% faster diagonally
- Canvas can't draw diagonal movement
- To round it to whole pixels
Which call gives the angle from the player to the mouse?
Math.atan(mx - px)Math.atan2(mx - px, my - py)Math.atan2(my - py, mx - px)Math.angle(px, py, mx, my)
The canvas is 480 pixels wide but shown 960 CSS pixels wide. The mouse is 300 CSS pixels from the canvas's left edge. What is mouse.x?
- 300
- 600
- 150
- 480