# How to get a Zombie to Chase Player at a certain distance?

`I am trying to develop a zombie game where the zombie only chases the player at a certain distance. For C#, what would i have to do to set his up? C# only please, Thank You.

``````using UnityEngine;
using System.Collections;

public class Zombie : MonoBehaviour
{
Transform player;               // Reference to the player's position.
//PlayerHealth playerHealth;      // Reference to the player's health.
//EnemyHealth enemyHealth;        // Reference to this enemy's health.
NavMeshAgent nav;               // Reference to the nav mesh agent.

void Awake ()
{

player = GameObject.FindGameObjectWithTag ("Player").transform;
//playerHealth = player.GetComponent <PlayerHealth> ();
//enemyHealth = GetComponent <EnemyHealth> ();
nav = GetComponent <NavMeshAgent> ();
}

void Update ()
{
// If the enemy and the player have health left...
//if(enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0)
//{
// ... set the destination of the nav mesh agent to the player.
nav.SetDestination (player.position);
//}
// Otherwise...
//else
//{
// ... disable the nav mesh agent.
//nav.enabled = false;
//}
}
}
``````

Here’s a very simplistic solution. I decided to break it up a bit so it would be more “step-by-step” than highly efficient.

``````public GameObject MyTarget; // Reference to whatever you want the zombie to react to
float DistanceToAttack = 5.0f; // Distance you want the zombie to begin attacking from

void Update()
{
// Calculate distance to target
float DistanceToTarget = CalculateDistance(MyTarget);

// If at the DistanceToAttack or less, then attack
if (DistanceToTarget <= DistanceToAttack)
{
Attack();
}
// Otherwise do nothing/idle
else
{
Idle();
{
}

// Simple implementation of Pythagorean formula to calculate distance
float CalculateDistance(GameObject MyTarget)
{
// Grab references to positions of player and zombie as a Vector3
Vector3 MyPosition = transform.position;
Vector3 TargetPosition = MyTarget.transform.position;

// Assuming you're working with x and z values here in 3d space, ignoring height.
// If not, use the y values instead.
float X = Math.Abs(MyPosition.x - TargetPosition.x);
float Z = Math.Abs(MyPosition.z - TargetPosition.z);
float D = Mathf.Sqrt(Math.Pow(X, 2) + Math.Pow(Y, 2));

return D;
}
``````

Have you thought about using Vector3.Distance? (When the Distance is in the range that you want, then trigger the chase)?

If you want zombies to follow your player at a certain distance then here’s an example pseudo-code for you.

If the zombies are too close, slow down their follow velocity.

Else if the zombies are at an optimum distance, keep the follow velocity unchanged.

Else if the zombies are too far away, speed up the follow velocity.

You can see this 1 here to see two ways of making your zombies follow the player. One of them uses the MoveTowards and the other uses the Lerp function.