Lesson 5 of 22, in world 2: Motion & Math
Vectors
A vector is just a pair of numbers (x, y). In games, vectors describe positions, directions, velocities, forces and distances — so they’re the single most-used tool in 2D maths. Good news: you only need a handful of operations.
Two ways to read a vector
- As a point: “the player is at (300, 200)”.
- As an arrow (a direction with a length): “move 3 right and 4 down”, which has length 5.
Drag the yellow handles at the tips of A and B. Each grid square is 40 px.
The operations you’ll use every day
| Operation | Formula | Game use |
|---|---|---|
| Add | (a.x+b.x, a.y+b.y) | Apply velocity to position: pos = pos + vel·dt |
| Subtract | (b.x−a.x, b.y−a.y) | Direction from enemy to player: player − enemy |
| Scale | (a.x·s, a.y·s) | Speed up / slow down a direction |
| Length | √(x² + y²) | Distance between things, current speed |
| Normalize | a / length(a) | Pure direction with length 1 |
| Dot product | a.x·b.x + a.y·b.y | ”Is the enemy in front of me?” (> 0 means yes) |
// Make an enemy chase the player at 120 px/s
const toPlayer = sub(player.pos, enemy.pos) // arrow from enemy to player
const direction = normalize(toPlayer) // length 1: just "which way"
enemy.pos = add(enemy.pos, scale(direction, 120 * dt))
// Is the player within 200 px?
if (length(toPlayer) < 200) enemy.alert = trueNormalize your input
Reading arrow keys gives an input vector like (1, 0) for right, or (1, 1) for down-right. But (1, 1) has length √2 ≈ 1.41, so diagonal movement is 41% faster. Normalize the input vector before multiplying by speed:
Hold →+↓ together. Both ships move at "200 px/s", but the pink one adds x and y input directly, so diagonally it moves at √2 × 200 ≈ 283 px/s. The cyan one normalizes the input first.
Key takeaways
- A vector is (x, y): a point or an arrow with direction and length.
- Subtract to get "from A to B", normalize to get a pure direction, scale to set speed.
- Normalize input vectors so diagonal movement isn’t faster.
Check yourself
Q1. Enemy at (100, 100), player at (400, 500). What is the distance between them?
Q2. What does normalize((0, −8)) return?
Q3. To make an enemy FLEE from the player, its direction is…
Exercises
- In the playground, make A and B point in opposite directions. What is A + B? When is it (0, 0)?
- Compute by hand: dot((1,0), (0,1)), dot((1,0), (1,0)), dot((1,0), (−1,0)). What does the sign tell you?
- Pseudo-code: a homing missile that turns toward the player. Which operations do you need?