- Home /
Target distance would only update closer
Hey so i have this script where i get the current target distance and it works fine when the target moves closer to the object but if the target moves further away it dosnt update the distance can somebody help me
public void TargetFinder()
{
foreach (var x in enemies)
{
float distance = (transform.position - x.transform.position).magnitude;
if (distance < currentTargetDistance)
{
myTarget = x;
displayText.text = "My target: " + x + "\n Distance to Target: " + distance; //skal fjernes nå det er helt klart
currentTargetDistance = distance;
}
}
}
Answer by Casiell · Nov 19, 2019 at 09:29 AM
Sure it doesn't update. You "distance" variable is the distance in this frame and "currentTargetDistance" is distance in previous frame. When moving away, "current..." will never be smaller than "distance".
I assume you want to find distance to the closest enemy? After the foreach, calculate distance to your current target and assign it to "currentTargetDistance"
Also this line
float distance = (transform.position - x.transform.position).magnitude;
can be switched to
float distance = Vector3.Distance(transform.position, x.transform.position)
Your answer
Follow this Question
Related Questions
target and look at random enemies 1 Answer
Suggestions for AI Selecting From Multiple Targets? 3 Answers
Unity 3D enemy stop distance? 1 Answer
Need Help With My AI Script 1 Answer