Game Dev 101
Progress
0/22

Lesson 5 of 22, in world 2: Motion & Math

Vectors

Time
About 20 min
Builds on
Coordinates & TransformsDelta Time & Fixed Timesteps

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.
LiveVector playground
Show

Drag the yellow handles at the tips of A and B. Each grid square is 40 px.

The operations you’ll use every day

OperationFormulaGame 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
Normalizea / length(a)Pure direction with length 1
Dot producta.x·b.x + a.y·b.y”Is the enemy in front of me?” (> 0 means yes)
JavaScript
// 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 = true

Normalize 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:

LiveThe diagonal speed bug

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

  1. In the playground, make A and B point in opposite directions. What is A + B? When is it (0, 0)?
  2. Compute by hand: dot((1,0), (0,1)), dot((1,0), (1,0)), dot((1,0), (−1,0)). What does the sign tell you?
  3. Pseudo-code: a homing missile that turns toward the player. Which operations do you need?