I've got a game object i need to rotate. It's current angle is player.rotation, the destination is targetAngle, both in degress, 0 to 359. I've got a function named rotateDirection(float sourceAngle, float destAngle) that needs to return -1 or 1 depending on whether the shortest way to reach the destination angle would be clockwise or counterclockwise.

For example - for sourceAngle 300 and destAngle 0 the function would return 1 for clockwise.

The solution is most probably going to leave me looking silly, and i usually don't like just asking for code, but my brain is completely broken so please help me with this one :)


This should do:

(((source-dest+360) mod 360)>180)?1:-1

The +360 is only necessary for languages with a fuzzy mod function. Note that most languages implement fuzzy mod.

  • \$\begingroup\$ hey, thanks for the answer. It seems to be returning -1 for source=3 dst = 38, which is an error... \$\endgroup\$ May 3 '11 at 23:38
  • \$\begingroup\$ Zaky: It returns 1 for source=3, dest=38. It reduces to 325>180 which is true, so it returns 1. \$\endgroup\$
    – Olhovsky
    May 3 '11 at 23:47
  • \$\begingroup\$ this does not work for me ! sorry for giving you a +1 \$\endgroup\$
    – Vishnu
    Jan 9 '12 at 11:11
  • 2
    \$\begingroup\$ @Vish No hard feelings. The code is fine, but of course there are countless ways of incorporating it into a whole in a way that does not produce the desired result. \$\endgroup\$ Jan 9 '12 at 14:24
  • \$\begingroup\$ I'm sorry eBusiness , but today I tried your code with the +360 thing and it worked. The word fuzzy mod function was what caused the confusion. Thank you :) \$\endgroup\$
    – Vishnu
    Jan 25 '12 at 7:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.