finding angle between one point and another point with ray

209 Views Asked by At

I'm trying to figure out the angle between the direction to an objective point relative to a player looking a certain direction.

This will be used in making a direction indicator for a game.

Here's a diagram made in Geogebra that shows the scenario

enter image description here

Updated diagram to avoid confusion

I have X,Y coordinates of the player and objective and I have the rotation of the player to work with.

1

There are 1 best solutions below

10
On BEST ANSWER

In two dimensions, you can use the scalar or dot product of two vectors:

$$ \mathbf{a}\cdot \mathbf{b}=\left(\begin{matrix} a_x \\ a_y \end{matrix}\right)\cdot\left(\begin{matrix} b_x \\ b_y \end{matrix}\right) = a_xb_x + a_yb_y = |\mathbf{a}| |\mathbf{b}|\cos\theta $$

where $\theta$ is the angle between the two vectors (and which could be either the acute or obtuse angle, depending on the directions of the vectors).

So, you'll need to find the vectors from

a) the player to the objective and

b) the player to the playerview

To get these vectors, imagine the player has coordinates $(p_x,p_y)$ and the objective has coordinates $(q_x,q_y)$. The vector from the player to the objective will then be:

$$\left(\begin{matrix} q_x - p_x \\ q_y-p_y \end{matrix}\right)$$ (You can do the same thing for the playerview if needed)

Then you need to calculate the magnitudes (lengths) of these vectors, and their scalar product via the middle relationship above. The angle will then be the inverse cosine of the dot product divided by the product of their magnitudes.

Edit:

Instead, if you know the angle for the playerview relative to north, you can use the dot product of the northwards (unit) vector (which is $\left(\begin{matrix} 0 \\ 1 \end{matrix}\right)$) and the vector above to find the angle from north to the objective, and then add (or subtract as necessary) the two angles to find the overall angle.