0
0
Unityframework~30 mins

Enemy patrol and chase patterns in Unity - Mini Project: Build & Apply

Choose your learning style9 modes available
Enemy patrol and chase patterns
📖 Scenario: You are creating a simple enemy character in a game. The enemy should patrol between two points and chase the player when the player is close enough.
🎯 Goal: Build an enemy script that makes the enemy move back and forth between two patrol points and chase the player when the player enters a certain distance.
📋 What You'll Learn
Create two patrol points as Vector3 variables
Create a chase distance threshold variable
Write code to move the enemy between patrol points
Write code to chase the player when within chase distance
💡 Why This Matters
🌍 Real World
Enemy patrol and chase patterns are common in many games to create engaging and dynamic AI behavior.
💼 Career
Understanding how to implement basic AI movement patterns is important for game developers and interactive experience creators.
Progress0 / 4 steps
1
Set up patrol points
Create two Vector3 variables called pointA and pointB with values new Vector3(0, 0, 0) and new Vector3(5, 0, 0) respectively.
Unity
Need a hint?

Use Vector3 pointA = new Vector3(0, 0, 0); and similarly for pointB.

2
Add chase distance variable
Add a public float variable called chaseDistance and set it to 3.0f.
Unity
Need a hint?

Declare public float chaseDistance = 3.0f; inside the class.

3
Implement patrol movement
Add a private Vector3 variable targetPoint initialized to pointB. In Update(), move the enemy towards targetPoint using Vector3.MoveTowards with speed 2f. When the enemy reaches targetPoint, switch targetPoint between pointA and pointB.
Unity
Need a hint?

Use Vector3.MoveTowards inside Update() and switch targetPoint when close.

4
Add player chase behavior
Add a public Transform variable called player. In Update(), check if the distance between the enemy and player.position is less than chaseDistance. If yes, move the enemy towards player.position with speed 3f. Otherwise, continue patrolling.
Unity
Need a hint?

Use an if statement to check distance to player.position and move accordingly.