Dot Product
The dot product takes two vectors and returns one number. It is the single most useful operation in game math: "is the enemy in front of me?", "is this surface facing the light?", "how much of my velocity goes into the wall?" are all dot products.
a · b = ax*bx + ay*by + az*bz
a · b = |a| * |b| * cos(θ) θ = the angle between a and bThe first line is how you compute it. The second line is what it means. When both vectors are unit length, the dot product is the cosine of the angle between them.
Reading the sign
For unit vectors the result is between -1 and 1:
â · b̂ |
Angle | Meaning |
|---|---|---|
1 |
0° | same direction |
> 0 |
under 90° | roughly the same way, "in front" |
0 |
90° | perpendicular, "beside" |
< 0 |
over 90° | roughly opposite, "behind" |
-1 |
180° | exactly opposite |
#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}; }
double dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y; }
Vec2 normalize(Vec2 v) { double l = std::sqrt(dot(v, v)); return {v.x / l, v.y / l}; }
int main() {
std::cout << std::fixed << std::setprecision(3);
Vec2 guard{0, 0};
Vec2 facing{1, 0}; // the guard looks along +X
Vec2 targets[] = {{5, 0}, {4, 3}, {0, 6}, {-3, 1}, {-2, 0}};
for (Vec2 t : targets) {
double d = dot(facing, normalize(t - guard));
const char* where = d > 0.001 ? "in front" : (d < -0.001 ? "behind" : "beside");
std::cout << "(" << t.x << ", " << t.y << ") dot=" << std::setw(6) << d << " " << where << "\n";
}
}(5.000, 0.000) dot= 1.000 in front
(4.000, 3.000) dot= 0.800 in front
(0.000, 6.000) dot= 0.000 beside
(-3.000, 1.000) dot=-0.949 behind
(-2.000, 0.000) dot=-1.000 behind
Field of view check
A guard sees in a cone of, say, 90°: 45° to each side of the facing direction. A target is inside the cone when the angle to it is less than 45°, which is the same as dot > cos(45°). Precompute the cosine once, and the per-target test is one dot product and one comparison, with no acos at all.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <numbers>
struct Vec2 { double x, y; };
Vec2 operator-(Vec2 a, Vec2 b) { return {a.x - b.x, a.y - b.y}; }
double dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y; }
double length(Vec2 v) { return std::sqrt(dot(v, v)); }
bool canSee(Vec2 eye, Vec2 facing, double fovDegrees, double range, Vec2 target) {
Vec2 to = target - eye;
double dist = length(to);
if (dist > range) return false;
if (dist < 1e-9) return true; // standing on the eye
double cosHalf = std::cos(fovDegrees * 0.5 * std::numbers::pi / 180.0);
return dot(facing, to) / dist >= cosHalf; // facing is already unit length
}
int main() {
std::cout << std::boolalpha;
Vec2 eye{0, 0}, facing{0, 1}; // looking "up" the screen
Vec2 tests[] = {{0, 5}, {3, 3.1}, {4, 3}, {-1, 8}, {0, 12}, {0, -2}};
for (Vec2 t : tests)
std::cout << "(" << t.x << ", " << t.y << ") seen: " << canSee(eye, facing, 90, 10, t) << "\n";
}(0, 5) seen: true
(3, 3.1) seen: true
(4, 3) seen: false
(-1, 8) seen: true
(0, 12) seen: false
(0, -2) seen: false
(3, 3.1) is just inside the 45° edge, (4, 3) is just outside it, and (0, 12) is in the cone but beyond the 10 m range. Real games add a raycast afterwards to check that no wall blocks the line of sight.
Move the mouse over the canvas below. The green cone is the guard's view; the dot is green when dot(facing, toTarget) >= cos(fov/2).
<canvas id="c" width="360" height="240" style="background:#111;display:block;max-width:100%"></canvas>
<div style="font:13px system-ui;color:#555;margin-top:4px">
FOV <input id="fov" type="range" min="10" max="180" value="90"> <span id="info"></span>
</div>
<script>
const c = document.getElementById('c'), ctx = c.getContext('2d');
const fov = document.getElementById('fov'), info = document.getElementById('info');
const eye = { x: 180, y: 200 }, facing = { x: 0, y: -1 }; // canvas y grows downward
let target = { x: 250, y: 90 };
function draw() {
const half = fov.value * Math.PI / 360, range = 180;
ctx.clearRect(0, 0, c.width, c.height);
const base = Math.atan2(facing.y, facing.x);
ctx.fillStyle = 'rgba(80,200,120,0.25)';
ctx.beginPath(); ctx.moveTo(eye.x, eye.y);
ctx.arc(eye.x, eye.y, range, base - half, base + half); ctx.closePath(); ctx.fill();
const tx = target.x - eye.x, ty = target.y - eye.y, len = Math.hypot(tx, ty) || 1;
const d = (facing.x * tx + facing.y * ty) / len;
const seen = d >= Math.cos(half) && len <= range;
ctx.strokeStyle = '#888'; ctx.beginPath(); ctx.moveTo(eye.x, eye.y); ctx.lineTo(target.x, target.y); ctx.stroke();
ctx.fillStyle = '#fff'; ctx.beginPath(); ctx.arc(eye.x, eye.y, 6, 0, 7); ctx.fill();
ctx.fillStyle = seen ? '#4caf50' : '#e53935'; ctx.beginPath(); ctx.arc(target.x, target.y, 8, 0, 7); ctx.fill();
info.textContent = 'dot = ' + d.toFixed(3) + ' cos(fov/2) = ' + Math.cos(half).toFixed(3) + (seen ? ' SEEN' : ' hidden');
}
c.addEventListener('mousemove', (e) => {
const r = c.getBoundingClientRect();
target = { x: (e.clientX - r.left) * c.width / r.width, y: (e.clientY - r.top) * c.height / r.height };
draw();
});
fov.addEventListener('input', draw);
draw();
</script>Lighting: Lambert's cosine law
A surface is brightest when light hits it head-on and dark when the light grazes it. The brightness is max(0, n̂ · l̂), where n̂ is the surface normal and l̂ points from the surface toward the light. This one line is the diffuse term of nearly every lighting model in games.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>
struct Vec3 { double x, y, z; };
double dot(Vec3 a, Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
Vec3 normalize(Vec3 v) { double l = std::sqrt(dot(v, v)); return {v.x / l, v.y / l, v.z / l}; }
int main() {
std::cout << std::fixed << std::setprecision(3);
Vec3 toLight = normalize({1, 2, 1});
struct Face { const char* name; Vec3 n; } faces[] = {
{"top ", {0, 1, 0}}, {"right ", {1, 0, 0}}, {"front ", {0, 0, 1}},
{"left ", {-1, 0, 0}}, {"bottom", {0, -1, 0}},
};
for (auto f : faces) {
double diffuse = std::max(0.0, dot(f.n, toLight));
std::cout << f.name << " brightness " << diffuse << "\n";
}
}top brightness 0.816
right brightness 0.408
front brightness 0.408
left brightness 0.000
bottom brightness 0.000
Dot product as "how much along"
If b̂ is a unit vector, a · b̂ is how far a reaches along b̂. With a character's forward vector, dot(velocity, forward) is the forward speed and dot(velocity, right) is the strafe speed, which is exactly what an animation blend tree needs. The next lesson but one, Projection and Reflection, builds on this.
Tip: The cosine meaning only holds for unit vectors. If you forget to normalize,
dotalso grows with the lengths, and a far-away target looks "more in front" than a close one. Normalize before you dot.
Test yourself
For two unit vectors, what does dot(a, b) == 0 mean?
- They point the same way
- They are perpendicular
- They point in opposite directions
- One of them is zero
A guard has a 120° field of view. Which test checks whether the unit direction d to a target is inside it?
dot(facing, d) >= cos(120°)dot(facing, d) >= cos(60°)dot(facing, d) <= 60dot(facing, d) >= 0.5 * 120
What is (1, 2, 3) · (4, -5, 6)?
- 12
- 32
- (4, -10, 18)
- -12