Bird
Raised Fist0
Unityframework~15 mins

Enemy patrol and chase patterns in Unity - Deep Dive

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of an enemy patrol pattern in Unity game development?
easy
A. To make the enemy jump randomly
B. To move the enemy between set points repeatedly
C. To make the enemy disappear and reappear
D. To make the enemy shoot projectiles continuously

Solution

  1. Step 1: Understand enemy patrol behavior

    Enemy patrol means moving the enemy between fixed points in a loop to simulate guarding or searching.
  2. Step 2: Identify correct behavior from options

    Only moving between set points repeatedly matches patrol behavior.
  3. Final Answer:

    To move the enemy between set points repeatedly -> Option B
  4. Quick Check:

    Enemy patrol = moving between points [OK]
Hint: Patrol means looping between points, not random actions [OK]
Common Mistakes:
  • Confusing patrol with attack or random movement
  • Thinking patrol involves shooting or disappearing
2. Which of the following is the correct way to check the distance between the enemy and player in Unity C#?
easy
A. float dist = enemy.position.Distance(player.position);
B. float dist = enemy.position - player.position;
C. float dist = Vector3.Distance(enemy, player);
D. float dist = Vector3.Distance(enemy.position, player.position);

Solution

  1. Step 1: Recall Vector3.Distance syntax

    The correct method to get distance between two Vector3 points is Vector3.Distance(point1, point2).
  2. Step 2: Check each option

    float dist = Vector3.Distance(enemy.position, player.position); uses Vector3.Distance with positions, which is correct. Others have syntax errors or wrong usage.
  3. Final Answer:

    float dist = Vector3.Distance(enemy.position, player.position); -> Option D
  4. Quick Check:

    Use Vector3.Distance(point1, point2) for distance [OK]
Hint: Use Vector3.Distance with positions, not subtract vectors directly [OK]
Common Mistakes:
  • Subtracting vectors without calling Distance method
  • Calling Distance on a Vector3 instance incorrectly
  • Passing transforms instead of positions
3. Given this code snippet for enemy chase, what will be the output if the player is 3 units away and chaseDistance is 5?
if (Vector3.Distance(transform.position, player.position) < chaseDistance) {
    Debug.Log("Chasing player");
} else {
    Debug.Log("Patrolling");
}
medium
A. No output
B. Patrolling
C. Chasing player
D. Error at runtime

Solution

  1. Step 1: Calculate distance and compare

    Distance is 3, chaseDistance is 5, so 3 < 5 is true.
  2. Step 2: Determine which branch runs

    Since condition is true, "Chasing player" is printed.
  3. Final Answer:

    Chasing player -> Option C
  4. Quick Check:

    Distance 3 < 5 triggers chase [OK]
Hint: Compare distance to chaseDistance to decide behavior [OK]
Common Mistakes:
  • Confusing less than with greater than
  • Assuming no output if condition true
  • Thinking code causes error
4. Identify the error in this patrol code snippet:
void Patrol() {
    int currentPoint = 0;
    transform.position = Vector3.MoveTowards(transform.position, patrolPoints[currentPoint].position, speed * Time.deltaTime);
    if (transform.position == patrolPoints[currentPoint].position) {
        currentPoint++;
        if (currentPoint >= patrolPoints.Length) {
            currentPoint = 0;
        }
    }
}
medium
A. currentPoint should be declared outside the method to keep its value
B. Vector3.MoveTowards is used incorrectly
C. Time.deltaTime should not be multiplied by speed
D. The if condition should use < instead of >

Solution

  1. Step 1: Check variable scope for currentPoint

    currentPoint is reset to 0 every time Patrol() runs, so it never increments properly.
  2. Step 2: Understand how to fix the scope issue

    Declaring currentPoint outside the method (as a class variable) preserves its value between calls.
  3. Final Answer:

    currentPoint should be declared outside the method to keep its value -> Option A
  4. Quick Check:

    Keep patrol index outside method to track progress [OK]
Hint: Keep patrol index as a class variable, not local [OK]
Common Mistakes:
  • Thinking MoveTowards usage is wrong
  • Confusing comparison operators in if
  • Misunderstanding Time.deltaTime usage
5. How can you combine patrol and chase behaviors so the enemy patrols until the player is within 4 units, then chases the player, and returns to patrol if the player moves away?
hard
A. Use a state variable to switch between patrol and chase based on distance checks
B. Call Patrol() and Chase() methods simultaneously every frame
C. Only use Chase() method and ignore patrol points
D. Use a timer to switch behaviors every 5 seconds regardless of player position

Solution

  1. Step 1: Understand behavior switching logic

    The enemy needs to switch between patrol and chase based on player distance dynamically.
  2. Step 2: Use a state variable to track current behavior

    A state variable (like enum or bool) can control which method runs each frame depending on distance.
  3. Step 3: Implement distance check to update state

    If player is closer than 4 units, set state to chase; else set to patrol.
  4. Final Answer:

    Use a state variable to switch between patrol and chase based on distance checks -> Option A
  5. Quick Check:

    State variable + distance check = behavior switch [OK]
Hint: Switch states based on distance, don't run both behaviors together [OK]
Common Mistakes:
  • Running patrol and chase at the same time causing conflicts
  • Ignoring player distance for switching
  • Using timers instead of distance checks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard