Vision Cones
An enemy that knows where you are through walls feels like a cheat; one that can't see you standing in front of it feels broken. Perception is the layer between the world and the decision-making: it decides what an agent knows. Sight is the most important sense in most games, and almost every engine models it the same way: a range, a field-of-view angle, and a line-of-sight test.
The three tests
To decide whether a guard at G, facing direction f (unit length), sees a target at T:
- Range:
|T - G| <= range. Cheapest, so it goes first. - Angle:
dot(f, normalize(T - G)) >= cos(fov / 2). Noacosneeded: compare cosines. (The dot product as "cosine of the angle" is covered in Math for Games.) - Line of sight: nothing solid between
GandT. In an engine this is a raycast against the physics world; on a grid we can walk along the segment and check the cells.
The order matters for performance: raycasts are expensive, and the first two tests reject most targets for the cost of a few multiplications.
using System;
string[] map =
{
"####################",
"#..................#",
"#......####........#",
"#..................#",
"#..G...............#",
"#..........##......#",
"#..........##......#",
"#..................#",
"####################",
};
var guard = new V2(3.5, 4.5); // centre of the G cell
var facing = new V2(1, 0); // looking east
const double Range = 12, Fov = 90;
double cosHalf = Math.Cos(Fov / 2 * Math.PI / 180);
Console.WriteLine("What the guard can see (* = visible floor):");
for (int y = 0; y < map.Length; y++)
{
var row = map[y].ToCharArray();
for (int x = 0; x < row.Length; x++)
if (row[x] == '.' && Sees(new V2(x + 0.5, y + 0.5)) == "SEEN") row[x] = '*';
Console.WriteLine(new string(row));
}
Console.WriteLine();
foreach (var (name, p) in new[] { ("A", new V2(10.5, 3.5)), ("B", new V2(3.5, 1.5)), ("C", new V2(17.5, 1.5)),
("D", new V2(14.5, 6.5)), ("E", new V2(17.5, 4.5)) })
Console.WriteLine(quot;target {name} at {p}: {Sees(p)}");
string Sees(V2 target)
{
V2 to = target - guard;
double dist = to.Len;
if (dist > Range) return "out of range";
if (Dot(facing, to * (1 / dist)) < cosHalf) return "outside the cone";
if (!LineOfSight(guard, target)) return "blocked by a wall";
return "SEEN";
}
bool LineOfSight(V2 a, V2 b)
{
int steps = (int)Math.Ceiling((b - a).Len / 0.1); // sample every 0.1 cells
for (int i = 1; i < steps; i++)
{
V2 p = a + (b - a) * ((double)i / steps);
if (map[(int)p.Y][(int)p.X] == '#') return false;
}
return true;
}
static double Dot(V2 a, V2 b) => a.X * b.X + a.Y * b.Y;
readonly record struct V2(double X, double Y)
{
public static V2 operator +(V2 a, V2 b) => new(a.X + b.X, a.Y + b.Y);
public static V2 operator -(V2 a, V2 b) => new(a.X - b.X, a.Y - b.Y);
public static V2 operator *(V2 a, double k) => new(a.X * k, a.Y * k);
public double Len => Math.Sqrt(X * X + Y * Y);
public override string ToString() => quot;({X:F1}, {Y:F1})";
}What the guard can see (* = visible floor):
####################
#.....**...........#
#.....*####..**....#
#....**********....#
#..G************...#
#....******##......#
#.....*****##......#
#.....*******......#
####################
target A at (10.5, 3.5): SEEN
target B at (3.5, 1.5): outside the cone
target C at (17.5, 1.5): out of range
target D at (14.5, 6.5): blocked by a wall
target E at (17.5, 4.5): out of range
The visible area is a wedge opening to the east, clipped by the range circle and with shadows behind the two wall blocks: the cells right behind each block stay dark even though they're inside the cone. That shadow is where a stealth player hides.
Note: Sampling a segment every 0.1 cells can miss a wall corner that the segment only grazes. Production grid code uses an exact traversal (Amanatides–Woo DDA, or a "supercover" Bresenham line); engines use a physics raycast. For gameplay it's also common to cast several rays (head, chest, feet) and count the player as seen if any of them reaches, so a player half-hidden behind a crate isn't invisible.
Try it: sneak past the guard
Move the pointer to move the player (the green dot). The guard sweeps its head left and right. Its cone is drawn with walls casting shadows; when it has line of sight to you, the cone turns red.
<style>
html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const walls = [ { x: 200, y: 60, w: 30, h: 90 }, { x: 300, y: 170, w: 90, h: 24 }, { x: 330, y: 40, w: 24, h: 60 } ];
const guard = { x: 90, y: 135, facing: 0, range: 260, fov: Math.PI / 2.5 };
const player = { x: 420, y: 230 };
let t = 0, hovering = false;
cv.addEventListener('pointermove', (e) => {
const r = cv.getBoundingClientRect();
player.x = (e.clientX - r.left) * (W / r.width);
player.y = (e.clientY - r.top) * (H / r.height);
hovering = true;
});
cv.addEventListener('pointerleave', () => { hovering = false; });
// Distance along a ray from (ox, oy) in direction (dx, dy) to the first wall or the canvas edge (slab test).
function castRay(ox, oy, dx, dy, maxLen) {
let best = maxLen;
for (const w of [...walls, { x: -1000, y: -1000, w: 1000, h: H + 2000 }, { x: W, y: -1000, w: 1000, h: H + 2000 },
{ x: -1000, y: -1000, w: W + 2000, h: 1000 }, { x: -1000, y: H, w: W + 2000, h: 1000 }]) {
let tmin = -Infinity, tmax = Infinity;
for (const [o, d, lo, hi] of [[ox, dx, w.x, w.x + w.w], [oy, dy, w.y, w.y + w.h]]) {
if (Math.abs(d) < 1e-9) { if (o < lo || o > hi) { tmin = Infinity; } continue; }
let t1 = (lo - o) / d, t2 = (hi - o) / d;
if (t1 > t2) [t1, t2] = [t2, t1];
tmin = Math.max(tmin, t1); tmax = Math.min(tmax, t2);
}
if (tmin <= tmax && tmin >= 0 && tmin < best) best = tmin;
}
return best;
}
function canSee() {
const dx = player.x - guard.x, dy = player.y - guard.y, d = Math.hypot(dx, dy);
if (d > guard.range) return false; // 1. range
if ((dx * Math.cos(guard.facing) + dy * Math.sin(guard.facing)) / d < Math.cos(guard.fov / 2)) return false; // 2. angle
return castRay(guard.x, guard.y, dx / d, dy / d, d) >= d - 0.5; // 3. line of sight
}
function frame() {
t += 1 / 60;
guard.facing = Math.sin(t * 0.6) * 0.7; // sweep the head
const seen = hovering && canSee();
ctx.fillStyle = '#14161f'; ctx.fillRect(0, 0, W, H);
// Cone: fan of rays, each stopped by the first wall, so walls cast shadows.
ctx.fillStyle = seen ? 'rgba(231, 76, 60, 0.35)' : 'rgba(255, 235, 130, 0.18)';
ctx.beginPath(); ctx.moveTo(guard.x, guard.y);
const RAYS = 90;
for (let i = 0; i <= RAYS; i++) {
const a = guard.facing - guard.fov / 2 + (guard.fov * i) / RAYS;
const len = castRay(guard.x, guard.y, Math.cos(a), Math.sin(a), guard.range);
ctx.lineTo(guard.x + Math.cos(a) * len, guard.y + Math.sin(a) * len);
}
ctx.closePath(); ctx.fill();
ctx.fillStyle = '#5c6378'; for (const w of walls) ctx.fillRect(w.x, w.y, w.w, w.h);
ctx.fillStyle = '#e67e22'; ctx.beginPath(); ctx.arc(guard.x, guard.y, 9, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = '#fff'; ctx.beginPath(); ctx.moveTo(guard.x, guard.y);
ctx.lineTo(guard.x + Math.cos(guard.facing) * 16, guard.y + Math.sin(guard.facing) * 16); ctx.stroke();
if (hovering) { ctx.fillStyle = '#2ecc71'; ctx.beginPath(); ctx.arc(player.x, player.y, 6, 0, Math.PI * 2); ctx.fill(); }
ctx.fillStyle = '#ddd'; ctx.font = '13px system-ui, sans-serif';
ctx.fillText(hovering ? (seen ? 'SEEN!' : 'hidden') : 'Move the pointer over the frame', 10, 18);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
</script>Making vision feel fair
| Technique | Why |
|---|---|
| Peripheral vision: a wide, short cone plus a narrow, long one | real eyes notice movement at the edges but recognise detail only in the centre |
| Detection meter: seeing you fills a bar, faster when close and well lit; detection happens when it's full | gives the player a moment to react; standard in stealth games |
| Lighting and stance scale the range | crouching in shadow should matter, and players expect it to |
| Show the cone (or a "?"/"!" icon) | the player can plan around rules they can see (see Field Notes: Design) |
| Check a few times per second, not every frame | perception is expensive and humans don't react in 16 ms anyway |
What happens after a sighting (suspicion rising, a last-known position, giving up the search) is the subject of Memory & Awareness. Engines ship ready-made sight senses: Unreal's UAIPerceptionComponent with a sight config (Unreal: EQS, StateTree & Perception); in Unity and Godot you usually write this check yourself with a physics raycast.
Test yourself
Why is the angle test written as dot(facing, dirToTarget) >= cos(fov / 2)?
- Because acos is not available in C#
- It avoids an acos per check: comparing cosines is equivalent and cheaper
- Because the dot product gives the distance
- It also checks line of sight
In which order should the three sight tests run?
- Raycast, angle, range
- Range, angle, then the raycast
- Angle, raycast, range
- The order doesn't matter for cost
Why do stealth games often cast several rays (head, chest, feet) to the player?
- To make the AI faster
- So a partly hidden player can still be detected, instead of being invisible whenever their centre point is covered
- Because a single ray can't hit a capsule
- To calculate the player's height