5

I want to be able to define a start and an end angle in a circle and then be able to come up with an algorithm that allows me to test if an angle is between the two angles (clockwise from start to end). Note that this has to work if the start point is 300deg and the end point is 45degrees. So for example,

start=10, end=50, test=20 (inside) start=270, end=90, test=350 (inside) start=270, end=90, test=180 (outside) start=310, end=20, test=0 (inside) start=310, end=20, test=200 (outside)

Thanks so much!

1 Answers1

11
  • Start by subtracting the start angle from all angles.
  • If any angles are now negative, add $360^\circ$ to them.
  • Now check to see if the middle angle is smaller than the end angle.

Example $1$: Is $180^\circ$ between $270^\circ$ and $90^\circ$?

  • Subtract to get start and end angles $0^\circ$, $-180^\circ$, with midpoint $-90^\circ$
  • Add $360^\circ$ to get $0^\circ$, $180^\circ$, with midpoint $270^\circ$
  • Since $270^\circ > 180^\circ$, $180^\circ$ is not between $270^\circ$ and $90^\circ$.

Example $2$: Is $0^\circ$ between $310^\circ$ and $20^\circ$?

  • Subtract to get start and end angles $0^\circ$, $-290^\circ$, with midpoint $-310^\circ$
  • Add $360^\circ$ to get $0^\circ$, $70^\circ$, with midpoint $50^\circ$
  • Since $50^\circ < 70^\circ$, $0^\circ$ is between $310^\circ$ and $20^\circ$.

And in C / C++:

bool isBetween(float start, float end, float mid) {     
    end = (end - start) < 0.0f ? end - start + 360.0f : end - start;    
    mid = (mid - start) < 0.0f ? mid - start + 360.0f : mid - start; 
    return (mid < end); 
}
  • The OP wanted to determine if an angle is between two angles going clockwise from start to end, and I think this may actually be the exact opposite. Of course, you can easily fix it by changing (mid < end) to (mid >= end). – Caleb Biddulph Apr 25 '21 at 19:37
  • Based on the application, you'll also want to consider what you want to happen when any two or three of start, end, and mid equal each other, and change between strict and non-strict inequalities accordingly. – Caleb Biddulph Apr 25 '21 at 19:40