In this Unity tutorial, you'll discover how to create a 3D enemy that follows the player character. We’ll cover how to make the enemy start pursuing the player when they enter a specified radius, stop following when the player moves out of range, and return to its original position when not tracking the player. This concise guide is perfect for adding engaging AI behavior to your game.
WATCH FULL TUTORIAL ON YOUTUBE
=========================================================
3 Unity Projects Only $70 - ON SALE!!!!
1. Water Sort 9000 Levels
2. Ball Sort Sort 9000 Levels
3. Sling Shot 250 Levels
Contact: unitycoderz2022@gmail.com
=========================================================
Script:
using UnityEngine;
public class EnemyFollow : MonoBehaviour
{
public Transform player; // The player's transform
public float moveSpeed = 3f; // Speed at which the enemy moves
public float followStartRadius = 5f; // Radius at which the enemy starts following the player
public float followStopRadius = 10f; // Radius at which the enemy stops following the player
public float rotationSpeed = 5f; // Speed at which the enemy rotates
private Vector3 originalPosition; // Original position of the enemy
private bool isFollowing = false; // Whether the enemy is currently following the player
void Start()
{
// Store the enemy's original position
originalPosition = transform.position;
}
void Update()
{
if (player != null)
{
float distance = Vector3.Distance(transform.position, player.position);
if (distance <= followStartRadius)
{
// Start following the player
isFollowing = true;
}
if (distance > followStopRadius && isFollowing)
{
// Stop following the player and return to the original position
isFollowing = false;
}
if (isFollowing)
{
// Calculate the direction to move
Vector3 direction = (player.position - transform.position).normalized;
// Move the enemy towards the player
transform.position += direction * moveSpeed * Time.deltaTime;
// Optional: Rotate the enemy to face the player
Quaternion lookRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * rotationSpeed);
}
else
{
// Move the enemy back to its original position
transform.position = Vector3.MoveTowards(transform.position, originalPosition, moveSpeed * Time.deltaTime);
// Stop moving if close enough to the original position
if (Vector3.Distance(transform.position, originalPosition) < 0.1f)
{
transform.position = originalPosition; // Snap to the original position to prevent floating point errors
}
}
}
}
}