Question by
madsgenefke · May 28, 2020 at 11:59 PM ·
programming
Find the closets target in 2D?
Hi everyone. I have been messing around with finding the closests target in 2D, but it does not seem to work
In the debug it says all the trenches instead of the one with the minimum distance. I suspect that it is because i set the minDist = 1000f in the beginning?
private void Update()
{
if (Trenches.Count > 0)
{
FindClosetsTrench();
}
}
public void FindClosetsTrench()
{
float minDist = 1000f;
foreach (Transform Trench in Trenches)
{
float distance = Vector2.Distance(Trench.position, transform.position);
if(distance < minDist)
{
minDist = distance;
Trench.GetComponent<Trench>().nearestTrench = true;
Debug.Log(Trench.name);
}
else
{
Trench.GetComponent<Trench>().nearestTrench = false;
}
}
}
Comment
Your answer
Follow this Question
Related Questions
How to use hold/tap interactions in new Input System 0 Answers
How to alter the bounce of a ball? Add force when hitting a ball? 0 Answers
Magnetic pieces being attached to each other and moving together ??? 0 Answers
Why is the 'parent' property on transform and not gameObject? 3 Answers
How to reference assets that are inside a folder?,Referencing assets in the scene 0 Answers