# Algorithm for taking the shortest path between two XY coordinates

I am making a simple game in Phaser (but the library doesn't really matter).

I have an enemy that is moving towards the player on a 2 dimensional grid. I have written some code that makes the enemy move towards the player:

moveEnemy(enemy){
var playerX = getPlayerX(); // a number
var playerY = getPlayerY(); // a number

// if the enemy X or Y coordinate is smaller or larger than the players,
// increase or decrease the enemy X or Y to move closer.
var newX = enemy.x > playerX ? enemy.x - 0.2 : enemy.x + 0.2;
var newY = enemy.y > playerY ? enemy.y - 0.2 : enemy.y + 0.2;
enemy.setPosition(newX, newY);
}


I expected this code to move the enemy towards the player in the shortest route possible. However, I get the following situation:

The green route is what I expected the enemy to take. In reality, the enemy follows the red line: first it goes down in a 45 degree angle, before going towards the player in a straight horizontal line. I'm at a loss how to make my enemies move along the green line.

• Welcome to the wonderful world of vectors. The library actually does matter here, because Phaser already has a vector class which is probably going to make this a lot easier.But I never used Phaser before, so I will leave the answer to this question to someone more familiar with the library. Sep 19, 2022 at 8:08
• Thanks Philipp, this helps me out a bit already. I'm a backend developer with zero experience in game development, so I got my homework cut out for me. Sep 19, 2022 at 8:08
• Thanks @Philipp, it took some reading but I figured it out. It's literally 2 lines of code in the Phaser library! Sep 19, 2022 at 17:38
• When you figured it out, then please post an answer to your own question so others can benefit from your knowledge. Sep 20, 2022 at 6:47

To solve this you need first to calculate deltaX = enemy.x - playerX and deltaY between the two points, and move the portion of distance in each direction, and he will move directly from A to B.
You'll need to know the distance to set constant speed. Find it with theDistance = Math.sqrt(dX*dX+dY*dY) with the squareroot-method.
I suggest unifying the direction by dividing deltaX/theDistance over the distance to get your direction, then you can just multiply this with the speed you want on the enemy.