# Help with calculating the angle to turn towards a target in a coordinatesystem

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?

-

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.
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