Closest actor, UE4 C++
There are several scenarios where you would like to find the closest actor to another object or world position. It could be for example a turret always aiming for the closest target. An AI attacking the closest target and so on and so forth.
In this example I have set up a scene with for movable cylinders and created a simple third person character player character to walk around with. I’m going to create a helper class in which I will have a method to return the closest object to a FVector and highlight the closest actor by changing its material.
To create the helper class and the actual function lets create a new class and derive it from UObject, I’m calling my class KC_Helpers.
From here we are goint to create our method. We want to be able to call it from blueprint and make it static. We need two parameters, the position to compare two and an array of actors.
UFUNCTION(BlueprintCallable) static AActor* GetClosestActor(FVector sourceLocation, TArray<AActor*> actors);
We are going to use a brute-force approach and the algorithm to get the closest actor works like this. We iterate over all our actors and compare the distance between the current actor and the position, if that distance is shorter than the preciously shortest distance we keep track of that actor and its distance instead of the previously one.
Declare variable to keep track of current closest distance. Set that variable to a high number. Declare variable to keep track of the current closest actor, For every actor. Calculate distance between current actor and position. If that distance is less than the previous closest distance. Save the current actor to the variable to keep track of closest actor. Return closest actor.
To put this to use we create a blueprint that dervies from our simple player character. In the Tick event we perform a SphereOverlActors, from its output we call our GetClosestActor then we change the material of the old closest character and to the new closest character.
To download the entire project go here; https://github.com/Klyx/UE4_Snippets