6

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 :)

Olhovsky
  • 3,519
  • 1
  • 24
  • 31
Zaky German
  • 1,136
  • 2
  • 12
  • 16

1 Answers1

5

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.

aaaaaaaaaaaa
  • 8,892
  • 1
  • 21
  • 35
  • hey, thanks for the answer. It seems to be returning -1 for source=3 dst = 38, which is an error... – Zaky German May 03 '11 at 23:38
  • Zaky: It returns 1 for source=3, dest=38. It reduces to 325>180 which is true, so it returns 1. – Olhovsky May 03 '11 at 23:47
  • this does not work for me ! sorry for giving you a +1 – Vishnu Jan 09 '12 at 11:11
  • 2
    @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. – aaaaaaaaaaaa Jan 09 '12 at 14:24
  • 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 :) – Vishnu Jan 25 '12 at 07:25
  • Yeah, fuzzy might be an inadequate description. It seems that fuzzy is for some reason the most popular kind of modulus. In any case, the way it is written is the safe method, if in doubt just leave the +360. – aaaaaaaaaaaa Jan 25 '12 at 10:51