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.

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 know the following:

  • my own position
  • my own facing (the angle im turned)
  • my targets position

What i would like some help with is how i calculate the shortes way to turn and the angle to turn. If i my position was (4,4) and i faced 90 degrees and my target was to face (1,1) where my target is, i know by drawing it on some paper that the shortest way to rotate is counter-clockwise 135 degrees.

But how do i calulate this? Ive tried using tangent, but using sine seems just as easy. Any ideas?

share|cite|improve this question
up vote 3 down vote accepted

Most computer systems have a function Atan2(x,y) which returns the polar angle of a point in the range $(-\pi,\pi]$ (check the endpoints-I think you get $+\pi$ for (-1,0). If you subtract your position from the target position and take Atan2 of the difference it will be the angle from you to target. Now subtract your heading and you have the angle to turn. If the result is outside $(-\pi,\pi]$, add or subtract $2\pi$ to get into the range. The nice thing of Atan2, as opposed to the regular atan, is it sorts out for you the signs and the branch of tangent.

You can use arcsin as well, but that requires measuring the distance to the target, which has an extra square root in it.

share|cite|improve this answer
For completeness: $$\arctan(x,y) = \begin{cases}\arctan(\frac y x) & \qquad x > 0 \\ \pi + \arctan(\frac y x) & \qquad y \ge 0 , x < 0 \\-\pi + \arctan(\frac y x) & \qquad y < 0 , x < 0 \\ \frac{\pi}{2} & \qquad y > 0 , x = 0 \\-\frac{\pi}{2} & \qquad y < 0 , x = 0 \\ \text{undefined} & \qquad y = 0, x = 0\end{cases}$$ – J. M. Dec 13 '10 at 16:35
@Jason94: I notice I missed a factor 2 in the amount to add or subtract. Fixed now. – Ross Millikan Dec 13 '10 at 19:09

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.