Hi there, I hope someone can help me with this or guide me to a video that explains it.
I have a 2d array of 5x5.
0 Y 0 0 0
0 0 0 0 Y // X represent the player melee unit
0 0 0 0 0 // Y represents enemy melee unit
0 0 X 0 0
Y 0 0 0 0
What I am trying to figure out is how do I determine which Y (Enemy) Unit is the closest to X, so that X can start moving closer to this units position?
For such a small array you could just iterate over it entirely and calculate the cost from X to any found Y, then remember the cheapest one. Cost would be defined over the difference in indices. So here your X is at [2][3]. The lowermost Y is at [0][4]. So we could calculate its cost as |(2-0)| + |(3-4)| = 3, which should be the “number of indices” one had to walk to reach Y from X. Then compare that to the current lowest Y, and if it’s a lower value, remember the indices of this Y. At the end you have the indices of the Y with the closest distance.
Super tired right now so i hope this still makes sense after i slept
At a very high level: Use Djikstra’s algorithm or A* to find the paths (and distances) to each enemy. Then pick the enemy at the smallest distance.
If your grid has no obstacles on it, you can do it without the pathfinding algorithms: Just calculate the Manhattan Distance to each enemy, and pick the closest one. (Edit: this is exactly as @Yoreki is describing above)
Pathfinding algorithms are definitely an intermediate level thing to implement. So if you’re a novice programmer, see if you can get away with the Manhattan distance approach.
Edit: To get a meaningful answer to this question you first need to decide what your definition of “closest” is. That depends on how your enemies move. Can they move diagonally? Can they move only horizontally and vertically? Can they go “off-grid” and fly in any straight line?
or at the very least, because there is nothing else to add, you can really milk Unity to do it for you.
you can convert your grid position into legit coordinates.
var player = new Vector2(playerGridX, playerGridY);
var enemy = new Vector2(enemyGridX, enemyGridY);
then compute the shortest airborne distance like this
var distance = Vector2.Distance(player, enemy);
but I’m not sure if any of this is useful for you.
searching for how to calculate a distance was only two words away the whole time.