**New course!**Every coder should learn

**Generative AI!**

+ 5

# How to find Shortest Distance Between Objects from Player object

a distance between player to from enemy so how to calculate shortest distance between the player to nearest enemy

8 Answers

+ 6

Brains🇳🇬 and Andre Daniel Awesome it exactly I wanted 👍👍👍

+ 3

By objects, do you mean two points on a graph? Simple, just use pythagoras theorem.
https://code.sololearn.com/cmmmeMs1MJqt/?ref=app

+ 3

Well, whether its 3d or not, the player and enemy has x and y coordinates. Just use the player's (x,y) and the enemy's (x,y) coordinates and calculate with the formula.
If you require shortest paths when walls are involved (and they have to open doors clumb steps etc), that becomes tricky. I'm unable to explain that one.
But a straight line distance, yeah my first method works.

+ 3

create an array..
find the distance using
x1=player.x-enem.x
x2=player.y-enem.y
dist=Math.sqrt(x1*x1+x2*x2);
find the distance between the player and each enemy with a loop.Each time storing the distance in an array.
Find the minimum value in the array and trace it back to which enemy has that distance..
thats the closest

+ 3

Oh yeah that works too. Put all the distances as calculated for each enemy in an array. Then run a for loop through the array to find the shortest distance.
psuedo-code:
enemies = [[3, 4], [7,2], [1,9]];
for(i = 0 to enemies.length)
distances[i] = calculate(playerY, playerY, enemies[i][0], enemies[i][1]);
function calculate(pX, pY, enemyX, enemyY) {
var distances = //pythagoraa theoram formula with enemy and player coords;
rerurn distances;
}
var closestDist, closestId;
for( x =0 to distances.length)
if( closest = undefined || distances[x] < closest) {
closestDist = distances[x];
closestId = x;
}
trace/output/print/write/display("Closest enemy = Enemy number " + closestId + " Its cordinates are (" + enemies[closestId][0] + "," + enemies[closestId][1] + ").");
Brains🇳🇬 added :)

+ 3

Andre Daniel perfect
that tells us the closest distance...
now he has to trace it back to which enemy has that dist

+ 2

Andre Daniel sure its works for two points 👍

0

How