Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|cite|improve this question
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
up vote 1 down vote accepted

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.

share|cite|improve this answer

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.

share|cite|improve this answer

Your Answer


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.