01 — Enemy AI Concepts

Sense → Decide → Act

Every game enemy, from a Goomba to a stealth-game guard, runs the same loop:

  1. Sense — gather facts: Can I see the player? How far? Am I at my waypoint?
  2. Decide — pick a behavior based on those facts and my current mood.
  3. 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 seconds

Why FSMs are the beginner-to-pro AI tool:

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:

  1. Range — Vector3.Distance (or better, compare squared magnitudes). Am I even close enough to matter?
  2. Field of view — angle between my facing and the direction to the player. A 110° cone means you can sneak up from behind.
  3. Line of sight — a Linecast from 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

Next: 02 - Setup and NavMesh