If you want some theory, I'll give you that.
The basic idea is to measure the distance to turn each way, and choose whichever is the shortest.
(Assuming +ve is clockwise)
Let D = targetangle - angle
clockwise turning distance C = (D) modulo 360 = D%360
anticlockwise turning distance A = (-D) modulo 360 = (-D)%360
And whichever is smallest we go that way.
Code:
D = targetangle - angle
Direction = SGN( (-D)%360 - D%360 )
(where 1=clockwise, -1=anticlockwise.)
Another way of looking at it is like this:
If D is between -180 and 0, then C=D+360 which is between 180 and 360.
Meanwhile A= -D which is between 0 and 180. Therefore A<C and we go anticlockwise.
If D is between -360 and -180, then C=D+360 which is between 0 and 180.
Meanwhile A= -D which is between 180 and 360. Therefore C<A and we go clockwise.
If D is between 0 and 180 then C=D, while A=360-D which is between 180 and 360. Therefore C<A and we go clockwise.
If D is between 180 and 360 then C=D, while A=360-D which is between 0 and 180. Therefore A<C and we go anticlockwise.
That logic can be written like this:
Code:
D = targetangle - angle
Direction = (D>0) XOR (ABS(D)>180)
(where 1=clockwise, 0=anticlockwise.)