# Enemy walks to the nearest player?

I'm trying making my enemy goes to the nearest player to him but what i get is kind of hesitated or shaking. I think is from the first line on Update but i don't know how to solve it. Here is my script

private Animator enemy_anim;
private NavMeshAgent mAgent;
private GameObject[] player;
public float dist;
public bool enemt_run, enemy_atack = false;

void Start()
{
mAgent = GetComponent<NavMeshAgent>();
enemy_anim = GetComponent<Animator>();
player = GameObject.FindGameObjectsWithTag("Player");
enemy_dirction();

}

void Update()
{
player_number = Random.Range(0,player.Length);
dist = Vector3.Distance(transform.position, player[player_number].transform.position);

if (player != null && dist <= 5.1f)
{
mAgent.destination = player[player_number].transform.position;
if (dist < 1.2f)
{
enemy_atack = true;
}
else
{
enemy_atack = false;
}
}
else
{
{
}
else
{
mAgent.destination = player[player_number].transform.position;

}
if (mAgent.remainingDistance <= 1.5f)
{
enemy_atack = true;
}
else
{
enemy_atack = false;
enemt_run = true;

}
}

mAgent.speed = 1.0f;

enemy_anim.SetBool("run", enemt_run);
enemy_anim.SetBool("attack", enemy_atack);
}// end update

void enemy_dirction()
{
{
}
else
{

}
}

• Rollbacked your edit because tagging your question [Solved] is not something we do on this site. Answering is encouraged even though a question is answered and people can see if a question is accepted or not by looking at the color of the "answers" number box anyways :) – Charanor Jun 22 '18 at 22:24

Every Update(), which is once per frame, you pick a new target with player_number = Random.Range(0,player.Length);, and if it's closer than 5.1 or if there are no dead_points, you steer towards it.

This means that if you are within 5.1 units of multiple enemies or if there are no dead_points, you bounce randomly between different targets every frame, causing a jitter.

You should only update player_number if:

1. you currently have no target and there is a close by target
2. OR your target becomes invalid, i.e. it died, it moved too far away, etc.

Edit: pick closest enemy each frame (still a suboptimal strategy, but it should eliminate the jittering)

player_number = 0;
for(int i=1; i<player.Length; i++) {
if (Vector3.Distance(transform.position, player[i].transform.position) <
Vector3.Distance(transform.position, player[player_number].transform.position)) {
player_number = i;
}
}

• You right but if i change these things other scripts need to change. Can I make enemy read the distance of the closet player and chose him rather than random.range ? – Omer Jun 22 '18 at 21:22
• you could, edited answer – Jimmy Jun 22 '18 at 21:42