Formula
Vector Magnitude (Length)
Measures how long a vector is — used for distance, speed, and normalization.
Intuition
A vector like (x, y) forms a right triangle from the origin. Its length is the hypotenuse.
Variables
- The vector whose length you want.
- Components of the vector along each axis.
Explanation
Magnitude tells you the size of a vector regardless of direction. In games, you use it to compute distance between points, determine speed from a velocity vector, or check whether an object is within range. For 2D games, drop the z term.
Where it shows up in games
Distance checks, speed calculation, range triggers, camera zoom constraints, and normalizing vectors before applying direction.
- For range checks, compare squared distance to squared range to avoid an expensive sqrt.
- Keep a small epsilon when comparing floating-point distances.
- Magnitude can be zero. Normalizing a zero vector causes division by zero or NaNs.
- Name vector operations clearly: magnitude, length, distance are related but not identical.
- Use a math library/vector type in production instead of ad-hoc objects when possible.
Implementation
JavaScript & C++function magnitude(v) {
return Math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
}
function distance(a, b) {
const dx = b.x - a.x;
const dy = b.y - a.y;
const dz = b.z - a.z;
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
// Example: check if enemy is in attack range
const enemy = { x: 10, y: 0, z: 3 };
const player = { x: 7, y: 0, z: 1 };
const attackRange = 5;
if (distance(player, enemy) <= attackRange) {
console.log("Enemy can attack");
}#include <cmath>
#include <iostream>
struct Vec3 {
float x, y, z;
};
float magnitude(const Vec3& v) {
return std::sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
}
float distance(const Vec3& a, const Vec3& b) {
float dx = b.x - a.x;
float dy = b.y - a.y;
float dz = b.z - a.z;
return std::sqrt(dx * dx + dy * dy + dz * dz);
}
int main() {
Vec3 player{7.0f, 0.0f, 1.0f};
Vec3 enemy{10.0f, 0.0f, 3.0f};
float attackRange = 5.0f;
if (distance(player, enemy) <= attackRange) {
std::cout << "Enemy can attack\n";
}
}