0
\$\begingroup\$

What is the easiest way to find the difference between two 2D rotations/directions?

I want to test if one rotation is within 10° of another. I would just subtract, but there are some problems because I want to keep each rotation between 0 and 359. E.g. 0 is within 10° of 359, but simple subtraction would claim that they're 359 degrees apart.

\$\endgroup\$
1
  • \$\begingroup\$ You don't have to tag your questions only with the software you are using. I added some appropriate tags; it doesn't really seem like this question is specific to the framework anyway. \$\endgroup\$ Commented May 14, 2014 at 0:01

3 Answers 3

2
\$\begingroup\$

This requires simple modulo arithmetic.

  1. Find the difference between two angles t1 and t2.
  2. Fix any angle differences that are greater than one full rotation.
  3. If angle exceeds 180 degrees, compare in the other direction.

Pseudo Code:

d = mod (abs (t1 - t2), 360) if (d > 180) d = 360 - d if (d <= 10) "Hooray!!!" 
\$\endgroup\$
1
  • \$\begingroup\$ Technically it may not require mod, but from your description in the actual question, I interpreted the situation as incoming angles may be outside the range [0, 360] but you want to restrict the result to [0, 360]. You can toss that part out if I misinterpreted your requirements. \$\endgroup\$ Commented May 14, 2014 at 2:05
1
\$\begingroup\$

One easy way is to check if the difference is greater than 180 or less than -180. If it is, you can add or subtract 360 to one of the values and then get your difference.

Example:

if(r1-r2 > 180) //r1 > r2 r1 = r1-360; else if(r1-r2 < -180) //r1 < r2 r1 = r1+360; //then check the difference diff = r1-r2; 
\$\endgroup\$
-1
\$\begingroup\$

Note that above fails for r1=720 and r2<=0. I would like this...

d = mod (r1 - r2), 360) if(d >= 180) //r1 > r2 d = d-360; else if(d < -180) //r1 < r2 d = d+360; 
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.