Closest enemy in a direction (left, right, forward, back)

did not check the previous replies so apologies if repeating something

The first question i would like to know is if you already have reference to all of the enemies

if the enemies are already known, it is easy to check from them, rather than query from the player

whether enemy references are in an array, or you have enemies check from their instance and then report their distance and direction to a manager, in either case it is just simpler because you 100% know that you are querying all of the enemies and there is no room for an odd edge case, compared to if you do an environment query

So if you check each enemy, the distance check is simple enough, adn for direction you just use a dot product test to check for alingment with a vector that is relative to the player. You can use arrow components to help visualize and set them to be visible in the game.

you can filter out any enemies not meeting the dot product threshold, and then from the remaining, sort distance array to find the nearest.

There is also some pretty stupid but simple ways as well. Everybody likes elegant code, but sometimes, especially if you are a beginner, something that is more simple may be best because you can count on it to work.
So my “too simple to fail” solution would be add four colliders to your character to represent each direction quadrant. You can make a collision channel so that these only test for collision with enemies. Then when you want to test for nearest enemy, you can just identify which quadrant and then get all the overlapping actors, and then sort them by distance.

It may seem like having those colliders would be inefficient, and it probably is, but if you filter them by channel and also only do the distance check by an event I would expect that you dont notice any problems from it. It should work fine for a beginner project, I would think.

2 Likes