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.