For the life of me I can't figure out how to make a object turn clockwise or counterclockwise based on which way is closer (because the direction switches from 0-360). I've tried searching google, but I have been unsuccessful so far. So I guess I figured I'd turn to the forums!
Any ideas?
Goblin
Going Clockwise or Counter-Clockwise [SOLVED]
Going Clockwise or Counter-Clockwise [SOLVED]
Last edited by g0bl1n on Sun Jun 05, 2011 5:41 pm, edited 2 times in total.
-
- Posts: 83
- Joined: Fri May 28, 2010 8:59 am
- Location: Perth, Australia
Re: Going Clockwise or Counter-Clockwise
Notice that no matter what, you are never more than 180 degrees from the orientation you are seeking. Consider that case special (because you can turn in either direction). In all other cases, one direction is a shorter rotation.
So compute the "delta": delta = current - desired
If the magnitude of delta is 180 degrees, turn either direction by 180 degrees.
If the magnitude of delta is less than 180 degrees, turn that far in the appropriate direction (which is determined by the sign of delta).
If the magnitude of delta is greater than 180 degrees, the shortest rotation crosses over the 0/360 wrap-around that is confusing you. That's OK, just either subtract or add (as appropriate) 360 degrees to delta so that it becomes 180 or smaller. Proceed as before.
Try drawing some of the cases (both simple and confusing) and the final algorithm should come to you.
So compute the "delta": delta = current - desired
If the magnitude of delta is 180 degrees, turn either direction by 180 degrees.
If the magnitude of delta is less than 180 degrees, turn that far in the appropriate direction (which is determined by the sign of delta).
If the magnitude of delta is greater than 180 degrees, the shortest rotation crosses over the 0/360 wrap-around that is confusing you. That's OK, just either subtract or add (as appropriate) 360 degrees to delta so that it becomes 180 or smaller. Proceed as before.
Try drawing some of the cases (both simple and confusing) and the final algorithm should come to you.
Code: Select all
float v = fmod(dest-current,360.0f);
if(v<0)
v+=360.0f;
if(v>180)
v-=360.0f;
printf("turn %f\n",v);
conceptually, the first "if" is with "fmod" to create a mathematical mod (fmod returns negative number if given negative number)