Getting Closest Enemy to focus on
below is a basic example of how you could find the closest character. in the example i used perceived actors as the potential targets but you could use whatever method you like to create the array of targets. i also did not add in the check for being dead since that could have many meanings / definitions, to check for death you would just add in another check before setting current closest.
on to how it works. the basic idea here is to loop through the list and check to see if the index we are testing is closer to the ai character (self) than the reference stored in the currentTarget variable. ok so first thing we need is a list of potential targets, used ai perception and got percieved actors to do this se we can only target things we see or hear. i then promoted the array to a variable to ensure it remains static while we run our script. next we need to set an initial value for the current closest so we get index 0 and set that as the closest, we do this so we have something valid to compare to in the next step otherwise it will try to get the distance to nothing which will always be the shortest. we are up to the loop now which is the main functionality of the script. the loop takes every index and gets its distance to the aicharacter then does the same with the current target, if the distance to the current index is less then or equal we set the current index actor to be the closest target and move on. there is also a check to ensure that the indexes being tested are not equal to 0, this is since we already set index 0 as the closest so theres no need to test it though this check may not actually be necessary. the last step is to output the closest target when the loop has completed.
answered Nov 20 '18 at 03:04 PM
I created a custom blueprint node that does just that if you want to see how to do it yourself here is the link to the tutorial:
Basically you feed it any array of actors and it will sort them closest to farthest or vice versa (boolean variable you can select on the node). It outputs a sorted array with the actors and their distance away from the target actor. You can then grab the 0 index of the sorted array and that will be the closest enemy to your player.
answered Nov 20 '18 at 06:05 PM
Nebula Games Inc
Follow this question
Once you sign in you will be able to subscribe for any updates here