Question by
Mergster · Jan 16, 2017 at 09:57 PM ·
c#movetowards
Why doesn't this script work right?
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);
}
}
}
Comment
Best Answer
Answer by KoenigX3 · Jan 16, 2017 at 10:13 PM
Change the logic in the foreach loop so instead of picking the object with bigger distance it will pick the nearest object.
curDist = int.MaxValue;
foreach (GameObject item in Targets)
{
float dist = (player.transform.position - item.transform.position).sqrMagnitude;
if (dist < curDist)
{
curDist = dist;
TargetToFind = item;
print (dist);
}
}
Your answer
Follow this Question
Related Questions
MoveTowards not moving accurately. Getting stuck on target. 2 Answers
Variable containing a transform is modifying the object's transform it is referenced to. 1 Answer
Vector3.MoveTowards Problems 0 Answers
Move Gameobject towards/away from position based on the proximity of 2 other objects 0 Answers