[Solved] - rotate towards closest angle
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]
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.
There's some resources on quaternions here.
Quaternions are overkill for this kind of problem. This thread from a few days ago should have what you're looking for.
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
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.
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.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement