Length, Distance and Normalize
A vector has a direction and a length (also called magnitude). Separating the two is one of the most common things you do: "move toward the player at 5 m/s" means take the direction toward the player, throw away its length, and give it a length of 5.
Length
The length of (x, y, z) comes from Pythagoras:
|v| = sqrt(x*x + y*y + z*z)The distance between two points is the length of the arrow between them: distance(a, b) = |b - a|.
#include <iostream>
#include <iomanip>
#include <cmath>
struct Vec3 { double x, y, z; };
Vec3 operator-(Vec3 a, Vec3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
double length(Vec3 v) { return std::sqrt(v.x * v.x + v.y * v.y + v.z * v.z); }
double lengthSq(Vec3 v) { return v.x * v.x + v.y * v.y + v.z * v.z; }
double distance(Vec3 a, Vec3 b) { return length(b - a); }
int main() {
std::cout << std::fixed << std::setprecision(3);
std::cout << "|(3, 4, 0)| = " << length({3, 4, 0}) << "\n";
std::cout << "|(1, 1, 1)| = " << length({1, 1, 1}) << "\n";
std::cout << "|(2,-3, 6)| = " << length({2, -3, 6}) << "\n";
Vec3 player{1, 0, 2}, chest{4, 0, 6};
std::cout << "distance = " << distance(player, chest) << "\n";
std::cout << "distance^2 = " << lengthSq(chest - player) << "\n";
}|(3, 4, 0)| = 5.000
|(1, 1, 1)| = 1.732
|(2,-3, 6)| = 7.000
distance = 5.000
distance^2 = 25.000
Squared length: skip the square root
sqrt is cheap on modern CPUs but not free, and more importantly you often don't need it. To compare distances, compare squared distances: if a < b (both positive) then a*a < b*b. A range check becomes lengthSq(d) <= range * range.
#include <iostream>
#include <iomanip>
struct Vec2 { double x, y; };
Vec2 operator-(Vec2 a, Vec2 b) { return {a.x - b.x, a.y - b.y}; }
double lengthSq(Vec2 v) { return v.x * v.x + v.y * v.y; }
int main() {
const Vec2 tower{0, 0};
const double range = 5.0;
Vec2 enemies[] = {{3, 3}, {4, 4}, {-5, 0}, {1, -4.9}};
for (Vec2 e : enemies) {
double d2 = lengthSq(e - tower);
bool inRange = d2 <= range * range;
std::cout << "(" << e.x << ", " << e.y << ") d^2=" << d2
<< (inRange ? " in range" : " out of range") << "\n";
}
}(3, 3) d^2=18 in range
(4, 4) d^2=32 out of range
(-5, 0) d^2=25 in range
(1, -4.9) d^2=25.01 out of range
Normalize: direction only
A vector of length 1 is a unit vector (written v̂, "v hat"). Normalizing divides every component by the length. Unit vectors are what you want for directions: facing, surface normals, the "forward" of a camera.
There is one trap: the zero vector has no direction, and dividing by its length divides by zero. Every engine has a "safe normalize" that returns zero (or a fallback) instead of NaN.
#include <iostream>
#include <iomanip>
#include <cmath>
struct Vec2 { double x, y; };
Vec2 operator-(Vec2 a, Vec2 b) { return {a.x - b.x, a.y - b.y}; }
Vec2 operator+(Vec2 a, Vec2 b) { return {a.x + b.x, a.y + b.y}; }
Vec2 operator*(Vec2 v, double s) { return {v.x * s, v.y * s}; }
double length(Vec2 v) { return std::sqrt(v.x * v.x + v.y * v.y); }
Vec2 normalizeSafe(Vec2 v, Vec2 fallback = {0, 0}) {
double len = length(v);
if (len < 1e-9) return fallback;
return v * (1.0 / len);
}
int main() {
std::cout << std::fixed << std::setprecision(3);
Vec2 enemy{0, 0}, player{6, 8};
const double speed = 2.5; // m/s
const double dt = 1.0;
Vec2 dir = normalizeSafe(player - enemy);
std::cout << "dir = (" << dir.x << ", " << dir.y << "), |dir| = " << length(dir) << "\n";
for (int t = 1; t <= 3; t++) {
enemy = enemy + dir * (speed * dt);
std::cout << "t=" << t << " enemy at (" << enemy.x << ", " << enemy.y << ")\n";
}
Vec2 zero = normalizeSafe({0, 0});
std::cout << "normalize(0,0) = (" << zero.x << ", " << zero.y << ")\n";
}dir = (0.600, 0.800), |dir| = 1.000
t=1 enemy at (1.500, 2.000)
t=2 enemy at (3.000, 4.000)
t=3 enemy at (4.500, 6.000)
normalize(0,0) = (0.000, 0.000)
Without normalizing, the enemy would move at |player - enemy| meters per second: fast when far away and slow when close. That is a classic beginner bug.
Diagonal movement
The same bug appears with keyboard input. Pressing right and up gives the input vector (1, 1), whose length is 1.414. Normalize it, or players will move 41% faster diagonally. Gamepad sticks are different: their magnitude already means "how far is the stick pushed", so only clamp them to length 1 instead of normalizing.
#include <iostream>
#include <iomanip>
#include <cmath>
struct Vec2 { double x, y; };
double length(Vec2 v) { return std::sqrt(v.x * v.x + v.y * v.y); }
Vec2 clampLength(Vec2 v, double maxLen) {
double len = length(v);
if (len <= maxLen) return v;
return {v.x / len * maxLen, v.y / len * maxLen};
}
int main() {
std::cout << std::fixed << std::setprecision(3);
Vec2 keys{1, 1};
std::cout << "raw keys length: " << length(keys) << "\n";
std::cout << "clamped keys length: " << length(clampLength(keys, 1)) << "\n";
Vec2 stickHalf{0.3, 0.4}; // stick pushed halfway
std::cout << "half stick length: " << length(clampLength(stickHalf, 1)) << "\n";
}raw keys length: 1.414
clamped keys length: 1.000
half stick length: 0.500
Test yourself
What is the length of (6, 8)?
- 14
- 10
- 48
- 100
Why compare lengthSq(d) <= r * r instead of length(d) <= r?
- It is more accurate for negative numbers
- It gives the same answer without a square root
- Squared lengths are always integers
- It works for the zero vector only
What should a safe normalize return for the zero vector?
- NaN
- (1, 0)
- A fallback such as (0, 0), not a division by zero
- The vector's length