+ 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

25th Jun 2018, 8:57 AM
Amar Dahake
8 ответов
+ 6
Brains🇳🇬 and Andre Daniel Awesome it exactly I wanted 👍👍👍
25th Jun 2018, 10:22 AM
Amar Dahake
+ 3
By objects, do you mean two points on a graph? Simple, just use pythagoras theorem. https://code.sololearn.com/cmmmeMs1MJqt/?ref=app
25th Jun 2018, 9:08 AM
Andre Daniel
Andre Daniel - avatar
+ 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.
25th Jun 2018, 9:19 AM
Andre Daniel
Andre Daniel - avatar
+ 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
25th Jun 2018, 9:25 AM
᠌᠌Code X
᠌᠌Code X - avatar
+ 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 :)
25th Jun 2018, 9:35 AM
Andre Daniel
Andre Daniel - avatar
+ 3
Andre Daniel perfect that tells us the closest distance... now he has to trace it back to which enemy has that dist
25th Jun 2018, 9:42 AM
᠌᠌Code X
᠌᠌Code X - avatar
+ 2
Andre Daniel sure its works for two points 👍
25th Jun 2018, 9:20 AM
Amar Dahake
0
How
25th Jun 2018, 9:29 AM
[No Name]