- Home /
Finding a the closest distance between a Ai and multipel enemys
Hello i am trying to make a A.I. that can find all of the enemys on the screen and target the closest one to it.I don't know how to do this can you help me on that please? So far i have made it so that it finds any enemy with a tag and goes for it,but of course this can cause the A.I. to go for a random enemy and that is bad. Here is the code:
void Ai(){
GameObject Target;
Vector2 TargetPos;
Target = GameObject.FindGameObjectWithTag ("Bad");
TargetPos = Target.transform.position;
transform.position = Vector2.MoveTowards (transform.position, TargetPos, Speed * Time.deltaTime);
}
Answer by unidad2pete · Aug 17, 2017 at 02:52 PM
public GameObject[] Enemies;
public GameObject Target;
public Vector2 TargetPos;
public float Speed = 5;
void Ai()
{
Enemies = GameObject.FindGameObjectsWithTag("Bad"); // Find all enemies
if(Enemies.Length > 0)
{
float distance = 10000;
for(int i = 0; i < Enemies.Length; i++)
{
if(Vector2.Distance(transform.position, Enemies[i].transform.position) < distance)
{
//If distance between you and this enemie is less than distance, set this enemy to target and the distance to distance to check
Target = Enemies[i];
distance = Vector2.Distance(transform.position, Enemies[i].transform.position);
TargetPos = Target.transform.position;
}
}
}
transform.position = Vector2.MoveTowards(transform.position, TargetPos, Speed * Time.deltaTime); // the most closer enemy
}
yup this is what i whanted but i have never used the "for" before so i am not really sure how it works guess i will just have to experiment thank you a lot :).
Answer by Destolos · Aug 17, 2017 at 10:05 AM
You can use GameObject[] Target = GameObject.FindGameObjectsWithTag ("Bad");
. That returns every Gameobject with the give tag.
Your answer
![](https://koobas.hobune.stream/wayback/20220612132918im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
A.I - what is better for player checking ? 0 Answers
Distribute terrain in zones 3 Answers
Distance before shooting issue. 1 Answer