I want this script to find the closest gameobject(relevant to my player ) tagged as enemy and move towards it but instead it moves towards the farthest enemy.
What do I have wrong?
public float speed = 2f;
public float minDistance = 0f;
private float range;
public float timeToDestroy;
GameObject[] Targets;
GameObject TargetToFind;
public GameObject player;
float curDist = 1;
void Start()
{
Destroy(gameObject, timeToDestroy); // 20sec
}
void Update ()
{
Targets = GameObject.FindGameObjectsWithTag("Enemy");
curDist = 1;
foreach (GameObject item in Targets)
{
float dist = (player.transform.position - item.transform.position).sqrMagnitude;
if (dist > curDist)
{
curDist = dist;
TargetToFind = item;
print (dist);
}
}
range = Vector2.Distance (transform.position, TargetToFind.transform.position);
if (range > minDistance) {
transform.position = Vector2.MoveTowards (transform.position, TargetToFind.transform.position, speed * Time.deltaTime);
}
timeToDestroy -= Time.deltaTime;
if (timeToDestroy <= 0) {
Destroy (gameObject);
}
}
}