It’s been odd though this week I’ve been asked about this rotation problem a few times, so it’s likely this may help others. This problem occurs when tweening rotation and the visual bug is that it’s not using the smallest rotation direction.
To reproduce this rotation problem or visual glitch it seems to only occur when the target angle is after PI and the current angle is before (and vice versa). To fix this is quite simple and it’s also interesting to see other peoples different mathematical approaches to solving this common problem, I’ve seen a few and a fix is a fix but here’s mine.
Below is an broken down version of the equation I’ve used to solve this problem where cA is your current radians and tA is your desired radians.
var diff:Number = tA-cA;
var pi:Number = Math.PI;
var pi2:Number = pi*2;
tA += Math.absdiff < pi ? 0 : diff>0 ? -pi2 : pi2;
Though this equation can easily be done in a single line which is my preference.
tA += Math.abstA-cA < Math.PI ? 0 : tA-cA>0 ? -Math.PI*2 : Math.PI*2;
Also further to this it’s important that the cA and the tA be normalized so they are not greater than Math.PI*2 or less than -Math.PI*2, if you’re not sure then this equation will sort this out for you.
cA = Math.abscA>pi2 ? cApi2 ? tA
I also understand some people may not prefer to be using the unit radians to express an angle. If this is you then it’s really no problem at all, just make sure cA and tA are in degrees and exchange Math.PI to the equivalent degrees value of 180.
tA += Math.abstA-cA < 180 ? 0 : tA-cA>0 ? -180*2 : 180*2;
I have also included an example SWF below to better demonstrate this situation with and without the fix. To undo the fix change the radio button selection to ‘normal’ to see the error. In this example the green line is the target angle, the blue line is the current angle and the grey line is the location of PI or 180 degrees.