# How to get the angle in the right triangle?

I have two coordinates which represent the mouse position with respect to the center of the screen ([0, 0] meaning the center, y increases downwards).

So, [0, 0] is one corner of the triangle, and mousePos is another. Now, the position of the mouse should determine the direction of of a small sprite representing the player (in radians).

When the mousePos is, say, [0, -100], right above the player (remember, y increases downwards), then the players direction is 0. When it's [100, 0], right to the player, the direction should be PI/2.

How do I get this? I know how to do it in a very long way, which would be very inefficient for the computer. What is the standard way of computing the angle?

-
You can use that $$\cos \alpha = \frac{A \cdot B }{\Vert A\Vert \cdot \Vert B \Vert}$$ where $\alpha$ is the angle between $A$ and $B$. I suggest that, first of all, you make the transformation $(x,y) \mapsto (x,-y)$ to use formulas that hold in $\mathbb{R}^2$. – talmid Jun 21 '12 at 18:14

## 2 Answers

You want to use the atan2 function if you have it.

Since different languages treat it in different ways, you may need to experiment: atan2(-y,x) or atan2(x,-y) will probably give you what you want.

-

We have $\text{MousePos}= (x_0,y_0)$. We change it to $(x_0,-y_0)$ to get the standard coordinate system. We want to calculate the angle between the $y$-axis and $(x_0,-y_0)$. Using the formula for the angle between to vectors, we get that $$\cos \alpha = \frac{(x_0,-y_0)\cdot(0,1)}{\sqrt{x_0^2 + y_0^2}}= \frac{-y_0}{\sqrt{x_0^2 + y_0^2}}$$

Then, $\alpha = \cos^{-1} \frac{-y_0}{\sqrt{x_0^2 + y_0^2}}$, however, this will probably give us an angle of $\pi/2$ when $(x_0,y_0)$ is to the left, and then we add a minus sign to get the formula: $$\cos^{-1} \frac{-y_0}{\sqrt{x_0^2 + y_0^2}}$$

The range of $\cos^{-1}$ depends on the implementation, so try some values of $(x_0,y_0)$, see if that works, and add or subtract $2\pi$ if necessary.

-