# [Solved] - rotate towards closest angle

This topic is 4065 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I've got a problem finding out how to rotate an angle towards another given angle in the shortest range. for example, the Source_angle=10° and the Target_angle=350°, then I want the Source to turn towards the Target by the shortest solution, in this case decreasing the Source (from 10° towards 350°). Did seem an easy task, allthough after trying diffrent approaches, I can't work it out, my code is always getting very long and not working 100% correctlly all the time. I'm sure there will be a simple solution, I've tried searching, but can't find what I'm looking after. Can someone point me in the right direction? [Edited by - R3D on May 3, 2007 1:21:29 PM]

##### Share on other sites
Quaternions could be the solution to this problem. Quaternions rotate using the shortest path, so rotating from 10 degrees to 350 degrees will be a 20 degree rotation.

There's some resources on quaternions here.

##### Share on other sites
Quaternions are overkill for this kind of problem. This thread from a few days ago should have what you're looking for.

##### Share on other sites
Thanks Zipster! I got it solved now based on the idea by TheAdmiral from that post.

Private Sub Main()    Dim source As Integer    Dim target As Integer    source = 159    target = 237        ' called foreach frame, untill source = target    source = RotFromTo(source, target) Mod 360    If source < 0 Then source = source + 360    If source >= 360 Then source = source - 360        ' at 1st frame > source = 160    ' at 2nd frame > source = 161    ' at 3rd frame > source = 162    End Sub' Rotate to target by shortest direction, in steps of 1°Private Function RotFromTo(source As Integer, target As Integer) As Integer    Dim difference As Integer    difference = Abs(source - target)    If difference < 180 And target > source Then RotFromTo = source + 1: Exit Function  ' cw    If difference < 180 And target < source Then RotFromTo = source - 1: Exit Function  ' ccw    If difference > 180 And target > source Then RotFromTo = source - 1: Exit Function  ' ccw    If difference > 180 And target < source Then RotFromTo = source + 1: Exit Function  ' cw    If difference = 180 Or difference = 0 Then RotFromTo = source + 1: Exit Function ' cw by choiceEnd Function

##### Share on other sites
I know this is solved already, but I just had this lying around.

This returns the shortest angle in radians from one orientation to another.

float shortestArc(float a, float b){    if (fabs(b-a) < M_PI)        return b-a;    if (b>a)        return b-a-M_PI*2.0f;    return b-a+M_PI*2.0f;}

Edit:
Since I see you're a VB kind of guy, I thought I should point out that M_PI = Π and that fabs() is the absolute value function.

• 38
• 12
• 10
• 10
• 9
• ### Forum Statistics

• Total Topics
631365
• Total Posts
2999585
×