01 — Enemy AI Concepts
Sense → Decide → Act
Every game enemy, from a Goomba to a stealth-game guard, runs the same loop:
- Sense — gather facts: Can I see the player? How far? Am I at my waypoint?
- Decide — pick a behavior based on those facts and my current mood.
- Act — move, attack, animate, bark a voice line.
Design your enemies as three separable layers and everything downstream gets easier. In this kit: TargetSensor senses, the EnemyAI state machines decide, and NavMeshAgent / A* paths / Rigidbody2D act. Swapping the act layer is exactly how the same brain works in 3D and 2D.
The Finite State Machine
The decide layer is a finite state machine (FSM): the enemy is always in exactly one state, each state runs its own logic, and named transitions switch between them.
stateDiagram-v2
[*] --> Patrol
Patrol --> Chase : vision sensor sees player
Chase --> Attack : player within attack range
Attack --> Chase : player escapes reach
Chase --> Patrol : lost sight for N secondsWhy FSMs are the beginner-to-pro AI tool:
- Each state is small and testable on its own.
- Bugs become questions like "which transition fired wrongly?" instead of "why is my 400-line Update weird?"
- Designers can read the diagram. You can read the diagram in six months.
In code, the kit uses the simplest honest form — an enum plus one method per state:
switch (CurrentState)
{
case State.Patrol: TickPatrol(); break;
case State.Chase: TickChase(); break;
case State.Attack: TickAttack(); break;
}
No framework, no magic — students can trace every line with a debugger. (Class-per-state and behavior trees are the growth path; see 06 - Tuning and Extending.)
The three classic detection tests
Detection sounds fancy but is three cheap checks, run cheapest-first:
- Range —
Vector3.Distance(or better, compare squared magnitudes). Am I even close enough to matter? - Field of view — angle between my facing and the direction to the player. A 110° cone means you can sneak up from behind.
- Line of sight — a
Linecastfrom my eyes to the player. If it hits a wall first, I can't see through it.
Combine all three and you have a stealth-game guard. Use range alone and you have a proximity mine. Everything between is tuning — which is why the kit packages them as one configurable TargetSensor you'll meet in 03 - The 3D Enemy.
Two more ideas that separate good enemies from annoying ones
- Hysteresis (the lose-sight timer): enemies shouldn't forget you the instant you break line of sight — a 2–3 second memory forgives corner-clipping and feels intelligent. Both chase states in this kit have it.
- Telegraphing: the platformer enemy pauses for 0.6 s (its "!" moment) before charging. Fair AI announces its intentions; frustrating AI acts on information the player never got to see.
Next: 02 - Setup and NavMesh