[Math] Determining direction based on (x,y) coordinates

coordinate systemsgeometry

I am making a $2D$ game where an enemy shoots a fireball at the player.

Both the player and the enemy have $(x, y)$ positions and are capable of facing in $8$ directions: UP, DOWN, LEFT, RIGHT, UPPER_RIGHT, UPPER_LEFT, LOWER_LEFT, LOWER_RIGHT.

Let's say the enemy's position is $(130, 100)$ and the player's position is $(145, 106)$. Based on those numbers, I know that I would want the enemy to shoot the fireball in the RIGHT direction because that is his best bet at hitting the player.

But how can I determine this using simple math? How can I determine which of the $8$ directions the enemy should shoot the fireball based on the $(x, y)$ coordinates?

Best Answer

You can use the following logic based on the player position $(x_p,y_p)$ and enemy position $(x_e,y_e)$.

First compute the slope of the line from the enemy to the player $$\frac{y_p-y_e}{x_p-x_e}$$

If the slope is zero, the player is on the same horizontal as the enemy, so the enemy will shoot either right or left.

If the slope is infinity (make sure you check before you try to calculate the slope) the player will be either directly up or down from the enemy.

If the slope is exactly $1$ or $-1$ then you will be on one of the diagonal directions exactly.

Otherwise, if the slope has magnitude $>2$ go with the closest vertical direction. I.e. if the slope is $-3$ and the player is below the enemy, you want to shoot straight down rather than lower_right. If the slope has magnitude $<1/2$ you want to shoot at the closest horizontal direction. Finally, if the slope $m$ has magnitude $2 > |m| > 1/2$ you want to shoot at the closest diagonal direction.