Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.

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?

share|improve this question
    
Look the line joining the coordinates. Then fix a north and try to consider the angle $\theta$ that the east-west line makes with the line joining the coordinates. Assign some angular range to each of the possible shooting directions, and I guess that should be it. You're basically "rounding up" to the nearest direction, if you may. –  Pedro Tamaroff Feb 28 '13 at 20:38
add comment

1 Answer 1

up vote 0 down vote accepted

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.

share|improve this answer
    
Thanks, pretty neat strategy. I think I have it working now. –  user64420 Feb 28 '13 at 22:24
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.