How to find the enemy, which is the closest to go?

Hello everyone.
I’m trying to make artificial intelligence. Enemies are on the list. The maximum will be about 30 units. How to find the enemy, which is the closest to go? Is there a ready-made solution or at least an algorithm?
I am using AILerp.

From documentation Searching for paths/Other types of paths:
https://arongranberg.com/astar/docs/callingpathfinding.html

// Start a multi target path, where endPoints is a Vector3[] array.
// The last parameter specifies if a path to all end points should be searched for
// or only to the closest one
seeker.StartMultiTargetPath (transform.position, endPoints, true);

You can just call this method with 3rd parameter set to false and it will give you path to the closest point. But this solution will just return path, not an enemy object or whatever you need

1 Like

The method is good, but I don’t have a pro version.

how to find closest enemy

for me in 3d was good Physics.OverlapSphereNonAlloc

@ Nikita A newbie uses google, and a professional asks on the forum and waits for magical unicorns.
Something like that.

public GameObject FindClosestEnemy(Vector3 playerPosition, List<GameObject> enemies)
    {
        GameObject closestEnemy = null;
        float closestDistance = Mathf.Infinity;

        foreach (GameObject enemy in enemies)
        {
            GraphNode node1 = AstarPath.active.GetNearest(transform.position, NNConstraint.Default).node;
            GraphNode node2 = AstarPath.active.GetNearest(enemy.transform.position, NNConstraint.Default).node;
            if (PathUtilities.IsPathPossible(node1, node2))
            {
                ai2.destination = enemy.transform.position;
                ai2.SearchPath();
                seeker.GetCurrentPath().BlockUntilCalculated();
                float distance = ai2.remainingDistance;
                print(enemy.name + "  " + distance);
                if (distance < closestDistance)
                {
                    closestEnemy = enemy;
                    closestDistance = distance;
                }
            }
        }
        return closestEnemy;
    }
3 Likes