- Home /
how to get AI to move to the closest of the same object?
Hello im having trouble with my basic AI program. it uses Navmesh and an agent. im trying to find the closest player to this Ai. Then get it to move to this AI. But the problem is there is more than one player and it will only move to one of the objects no the closest. how can i achieve this? this is what i have got so far :
using UnityEngine;
using System.Collections;
public class AI_test : MonoBehaviour {
// Use this for initialization
void Start () {
agent = GetComponent<NavMeshAgent> ();
}
NavMeshAgent agent;
// Update is called once per frame
void Update () {
GameObject target = FindClosestEnemy ();
agent.SetDestination(target.transform.position);
}
GameObject FindClosestEnemy() {
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("Player");
GameObject closest = null;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in gos) {
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closest = go;
distance = curDistance;
}
}
return closest;
}
}
thanks for your help.
Comment
I am confused by this. Are you trying to move the player towards the AI or was that a typo? If you are you need to use sendmessage and stuff. If not just try to make a few slight adjustments to the script:
private Nav$$anonymous$$eshAgent agent;
void Start () {
agent = GetComponent<Nav$$anonymous$$eshAgent> ();
}
void Update () {
TargetClosestEnemy();
}
GameObject TargetClosestEnemy() {
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("Player");
GameObject closest = gos[0];
float distance = $$anonymous$$athf.Infinity;
foreach (GameObject g in gos) {
float curDistance = (g.transform.position-transform.position).magnitude;
if (curDistance < distance) {
closest = g;
distance = curDistance;
}
}
agent.SetDestination(closest.transform.position);
}