[Math] Help with calculating the angle to turn towards a target in a coordinatesystem

trigonometry

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?

Best Answer

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.

Related Question