Building Enemy Aggro with Vector3.MoveTowards in Unity
13 Aug 26 (2mo ago)
When building enemy AI in Unity, Vector3.MoveTowards is the standard tool for simple, straight-line "aggro" (chasing the player). It moves an object at a constant speed without overshooting its destination.
How It Works
Vector3.MoveTowards(Vector3 current, Vector3 target, float maxDistanceDelta)
current: The enemy's starting position (transform.position).target: The destination (playerTarget.position).maxDistanceDelta: The maximum distance moved per frame. Set this tospeed * Time.deltaTimefor smooth, frame-rate-independent movement.
Every frame, Unity calculates the remaining distance. If it is smaller than your max distance delta, it snaps directly to the target, completely preventing manual math jitter.
The Basic Aggro Script
Attach this MonoBehaviour to your enemy GameObject. It updates the transform every frame and handles basic rotation:
using UnityEngine;
public class EnemyAggro : MonoBehaviour
{
[SerializeField] private Transform playerTarget;
[SerializeField] private float moveSpeed = 5f;
void Update()
{
if (playerTarget == null) return;
// Move toward the target at a constant speed
transform.position = Vector3.MoveTowards(
transform.position,
playerTarget.position,
moveSpeed * Time.deltaTime
);
// Rotate to face the player
transform.LookAt(playerTarget);
}
}
Tip: While this movement logic must live in a MonoBehaviour, professional projects often keep the AI "brain" (detection radius, cooldowns) in separate, plain C# utility classes to keep the hierarchy clean.
Limitations & Alternatives
MoveTowards is perfect for flying enemies or simple environments without obstacles. However, it ignores physics and cannot navigate around walls. Choose your movement method based on your level design:
| Method | Best For | Avoids Walls? | Physics-Safe? |
|---|---|---|---|
Vector3.MoveTowards | Simple aggro, flying enemies, projectiles | No | No (Bypasses colliders) |
Rigidbody.MovePosition | Physics-driven characters, pushable enemies | No | Yes |
NavMeshAgent | Complex 3D environments, pathfinding | Yes (Built-in A*) | Yes (Kinematic) |
Vector3.Lerp | UI transitions, dynamic camera smoothing | No | N/A |