0
0
Unityframework~15 mins

Enemy patrol and chase patterns in Unity - Deep Dive

Choose your learning style9 modes available
Overview - Enemy patrol and chase patterns
What is it?
Enemy patrol and chase patterns are ways to make game characters move and react in a believable way. Patrol means the enemy moves along a set path or area, watching for the player. Chase means the enemy follows the player when detected. These patterns help create challenge and excitement in games by making enemies seem smart and alive.
Why it matters
Without patrol and chase patterns, enemies would stand still or move randomly, making the game boring and unrealistic. These patterns create tension and strategy, as players must avoid or confront enemies that actively search and pursue them. They make games more fun and immersive by simulating real behaviors.
Where it fits
Before learning this, you should understand basic Unity concepts like GameObjects, components, and scripting in C#. After mastering patrol and chase, you can explore advanced AI techniques like pathfinding, state machines, and behavior trees.
Mental Model
Core Idea
Enemy patrol and chase patterns are simple rules that control how enemies move and react to the player to create believable behavior.
Think of it like...
It's like a security guard walking a hallway (patrol) and running after an intruder when spotted (chase).
┌─────────────┐       ┌─────────────┐
│   Patrol    │──────▶│  Detect     │
│  (walk path)│       │  Player?    │
└─────────────┘       └─────┬───────┘
                             │Yes
                             ▼
                      ┌─────────────┐
                      │   Chase     │
                      │  (follow)   │
                      └─────────────┘
Build-Up - 7 Steps
1
FoundationBasic enemy movement setup
🤔
Concept: How to move an enemy GameObject in Unity using simple scripts.
Create a new C# script that moves the enemy forward at a constant speed. Attach it to the enemy GameObject. Use Transform.Translate or Rigidbody movement in FixedUpdate to move smoothly.
Result
The enemy moves forward continuously in the game scene.
Understanding how to move objects is the foundation for creating any patrol or chase behavior.
2
FoundationDefining patrol points
🤔
Concept: Setting up points in the scene for the enemy to move between during patrol.
Place empty GameObjects in the scene as patrol points. Store them in an array or list in the enemy script. The enemy will move from one point to the next in order.
Result
The enemy moves between fixed points, creating a patrol path.
Using patrol points breaks down movement into manageable steps and creates predictable enemy paths.
3
IntermediateImplementing patrol logic
🤔Before reading on: do you think the enemy should instantly switch direction at patrol points or smoothly turn? Commit to your answer.
Concept: Making the enemy move between patrol points and turn smoothly when changing direction.
In the script, check if the enemy is close to the current patrol point. If yes, switch to the next point. Use Quaternion.Slerp or Vector3.RotateTowards to smoothly rotate the enemy toward the next point while moving.
Result
The enemy patrols smoothly along the path, turning naturally at points.
Smooth turning makes enemy movement look natural and less robotic, improving player immersion.
4
IntermediateDetecting the player
🤔Before reading on: do you think enemies should detect the player instantly or only within a certain range and angle? Commit to your answer.
Concept: Using distance and angle checks to detect the player realistically.
Use Vector3.Distance to check if the player is within a detection radius. Use Vector3.Angle between enemy forward and direction to player to check if player is in the enemy's field of view. Combine these to decide if the player is detected.
Result
The enemy detects the player only when close enough and in front, mimicking real sight.
Combining distance and angle checks prevents enemies from detecting players through walls or behind them, making gameplay fair.
5
IntermediateSwitching from patrol to chase
🤔Before reading on: do you think the enemy should immediately chase or wait briefly after detecting the player? Commit to your answer.
Concept: Changing enemy behavior from patrolling to chasing when the player is detected.
Add a state variable to track if the enemy is patrolling or chasing. When detection conditions are met, switch to chase state. In chase state, move enemy toward player position instead of patrol points.
Result
The enemy stops patrolling and starts following the player when detected.
State switching is key to making enemies react dynamically and feel intelligent.
6
AdvancedChase behavior with smooth pursuit
🤔Before reading on: do you think chasing means moving directly to the player or predicting player movement? Commit to your answer.
Concept: Making the enemy chase smoothly and realistically by predicting player movement.
Instead of moving directly to the player's current position, calculate a predicted position based on player's velocity. Use Vector3.Lerp or SmoothDamp to move enemy smoothly toward predicted position. This avoids jittery or unrealistic chasing.
Result
The enemy chases the player smoothly, anticipating movement and creating a challenging pursuit.
Predictive chasing improves enemy behavior realism and player experience by avoiding robotic movement.
7
ExpertHandling lost player and return to patrol
🤔Before reading on: do you think enemies should chase forever or give up after losing sight? Commit to your answer.
Concept: Making enemies stop chasing if the player escapes and return to patrol gracefully.
Track time since last player sighting. If the player is out of detection range or view for a set time, switch enemy state back to patrol. Optionally, move enemy to last known player position before resuming patrol. This prevents endless chasing and adds realism.
Result
Enemies chase the player only while visible, then return to patrol if the player escapes.
Knowing when to give up chasing prevents frustrating gameplay and simulates realistic enemy behavior.
Under the Hood
Enemy patrol and chase patterns rely on updating enemy position and rotation every frame based on current state. Patrol uses a list of waypoints and moves enemy toward the next point, switching points when close. Detection uses geometric calculations like distance and angle to check player presence. Chase updates target position dynamically, often predicting player movement. State variables control behavior switching. Unity's Update or FixedUpdate methods run these calculations continuously, creating smooth movement and reactions.
Why designed this way?
This design separates concerns: movement, detection, and state management. It uses simple math for performance and clarity. Alternatives like complex AI or physics-based detection exist but are heavier. This approach balances realism and efficiency, suitable for many game types. It also allows easy extension with more states or behaviors.
┌───────────────┐
│ Patrol State  │
│ Move to point │
└──────┬────────┘
       │
       ▼ Detect player?
┌───────────────┐     No
│ Detection     │─────────────┐
│ (distance +   │             │
│  angle check) │             │
└──────┬────────┘             │
       │Yes                   │
       ▼                     ▼
┌───────────────┐       ┌───────────────┐
│ Chase State   │       │ Continue      │
│ Move to player│       │ Patrol        │
└──────┬────────┘       └───────────────┘
       │
       ▼ Lost player?
┌───────────────┐
│ Return to     │
│ Patrol        │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do enemies always detect the player instantly when close? Commit yes or no.
Common Belief:Enemies detect the player immediately as soon as they are near.
Tap to reveal reality
Reality:Enemies detect the player only if within a certain distance and inside their field of view angle.
Why it matters:Without angle checks, enemies would detect players behind them or through walls, making gameplay unfair and frustrating.
Quick: Do you think chasing means enemies always move directly to the player's current position? Commit yes or no.
Common Belief:Chasing means moving straight to where the player is right now.
Tap to reveal reality
Reality:Good chase behavior predicts player movement to avoid jittery or unrealistic pursuit.
Why it matters:Direct chasing can cause enemies to overshoot or jitter, breaking immersion and making the chase feel unnatural.
Quick: Do enemies chase the player forever once detected? Commit yes or no.
Common Belief:Once an enemy detects the player, it chases endlessly until caught.
Tap to reveal reality
Reality:Enemies usually give up chasing after losing sight for some time and return to patrol.
Why it matters:Endless chasing can frustrate players and make the game feel unfair or broken.
Quick: Do you think patrol paths must be complex to be effective? Commit yes or no.
Common Belief:Patrol paths need to be complex and random to challenge players.
Tap to reveal reality
Reality:Simple patrol paths with a few points can create effective and predictable enemy behavior that players can learn and strategize against.
Why it matters:Overcomplicating patrols can confuse players and increase development complexity without improving gameplay.
Expert Zone
1
Using state machines to manage patrol, chase, and other behaviors improves code clarity and scalability.
2
Incorporating line-of-sight checks with raycasting prevents enemies from detecting players through obstacles.
3
Adjusting detection parameters dynamically based on game difficulty or enemy type creates richer gameplay experiences.
When NOT to use
For very complex AI requiring learning or adaptation, use behavior trees or machine learning instead. For simple background enemies, static or random movement may suffice without patrol/chase logic.
Production Patterns
In real games, patrol and chase are combined with animations, sound cues, and pathfinding systems like Unity's NavMesh for smooth navigation around obstacles. Enemies often have multiple states like alert, search, and attack layered on top of patrol and chase.
Connections
Finite State Machines
Enemy patrol and chase patterns are often implemented using finite state machines to manage behavior states.
Understanding state machines helps organize enemy logic cleanly and enables easy addition of new behaviors.
Human Attention and Perception
Enemy detection mimics how humans focus attention within a field of view and ignore distractions outside it.
Knowing human perception principles guides realistic enemy detection design, improving player immersion.
Security Guard Patrols in Real Life
Enemy patrol and chase patterns are inspired by how security guards monitor areas and respond to intruders.
Studying real-world patrol behavior informs game AI design, making enemies feel believable and strategic.
Common Pitfalls
#1Enemy detects player through walls or behind them.
Wrong approach:if (Vector3.Distance(enemy.position, player.position) < detectionRange) { detected = true; }
Correct approach:if (Vector3.Distance(enemy.position, player.position) < detectionRange && Vector3.Angle(enemy.forward, player.position - enemy.position) < fieldOfViewAngle) { detected = true; }
Root cause:Ignoring the enemy's field of view angle causes detection in unrealistic directions.
#2Enemy instantly switches direction at patrol points causing jerky movement.
Wrong approach:enemy.transform.LookAt(nextPatrolPoint.position); enemy.transform.position = Vector3.MoveTowards(...);
Correct approach:enemy.transform.rotation = Quaternion.Slerp(enemy.transform.rotation, Quaternion.LookRotation(direction), turnSpeed * Time.deltaTime); enemy.transform.position = Vector3.MoveTowards(...);
Root cause:Not smoothing rotation leads to unnatural, robotic enemy movement.
#3Enemy chases player forever even after losing sight.
Wrong approach:if (detected) { ChasePlayer(); } else { Patrol(); }
Correct approach:if (detected) { lastSeenTime = Time.time; ChasePlayer(); } else if (Time.time - lastSeenTime < chaseTimeout) { ChasePlayer(); } else { Patrol(); }
Root cause:Not tracking time since last sighting causes endless chasing behavior.
Key Takeaways
Enemy patrol and chase patterns create believable and engaging enemy behavior by controlling movement and reactions.
Combining distance and angle checks for player detection prevents unrealistic enemy awareness.
Smooth turning and predictive chasing improve the natural feel of enemy movement.
State management allows enemies to switch between patrolling and chasing dynamically.
Handling lost player situations prevents frustrating endless chases and enhances gameplay balance.