- Home /
Question by
Hathakas · Sep 08, 2015 at 12:44 AM ·
targetingclosesttargetting
How to target closest enemy, but with a min/max range
Hey guys,
I've been using this cool code and it works great for what I need. I just can't figure out how to have a minimum range. I don't want to target something that is too close for example.
Thanks a lot!
public GameObject FindClosestEnemy()
{
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("Copper");
GameObject closest = null;
float distance2 = Mathf.Infinity;
float distance = 15;
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;
//target = go;
}
}
return closest;
Debug.Log(closest);
}
Comment
Best Answer
Answer by Bunny83 · Sep 08, 2015 at 01:24 AM
Since you iterate through all possible targets, just add your criteria to the if statement:
public GameObject FindClosestEnemy(float min, float max)
{
GameObject[] gos = GameObject.FindGameObjectsWithTag("Copper");
GameObject closest = null;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
// calculate squared distances
min = min * min;
max = max * max;
foreach (GameObject go in gos)
{
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance && curDistance >= min && curDistance <= max)
{
closest = go;
distance = curDistance;
}
}
return closest;
}
Your answer
Follow this Question
Related Questions
Choose a Random Tag 1 Answer
find closest target? 1 Answer
geting the closest object from a array 2 Answers
Move an object towards closest enemy. 1 Answer
How to determine a "cone of influence" used for targeting an object. 2 Answers