Determine if angle lies between 2 other angles

后端 未结 12 1590
予麋鹿
予麋鹿 2020-12-15 05:47

I am trying to figure out whether a angle lies between 2 other angles. I have been trying to create a simple function to perform this but none of my techniques will work for

12条回答
  •  被撕碎了的回忆
    2020-12-15 06:33

    I know this post is old, but there doesn't seem to be an accepted answer and I have found the following approach to be quite reliable. Although it might be more than what you need. It supports angle ranges larger than 180 degrees (as well as larger than 360 degrees and negative angles). It also supports decimal accuracy.

    The method uses this normalize() helper function to convert angles into the right space:

    float normalize( float degrees )
    {
      //-- Converts the specified angle to an angle between 0 and 360 degrees
      float circleCount = (degrees / 360.0f);
      degrees -= (int)circleCount * 360;
      if( 0.0f > degrees )
      {
        degrees += 360.0f;
      }
      return degrees;
    }
    

    Here's the solution:

    bool isWithinRange( float start, float end, float angle )
    {
      if( fabsf( end - start ) >= 360.0f )
      {
        //-- Ranges greater or equal to 360 degrees cover everything
        return true;
      }
    
      //-- Put our angle between 0 and 360 degrees
      float degrees = normalize( angle );
    
      //-- Resolve degree value for the start angle; make sure it's
      //   smaller than our angle.
      float startDegrees = normalize( start );
      if( startDegrees > degrees )
      {
        startDegrees -= 360.0f;
      }
    
      //-- Resolve degree value for the end angle to be within the
      //   same 360 degree range as the start angle and make sure it
      //   comes after the start angle.
      float endDegrees = normalize( end );
      if( endDegrees < startDegrees )
      {
        endDegrees += 360.0f;
      }
      else if( (endDegrees - startDegrees) >= 360.0f )
      {
        endDegrees -= 360.0f;
      }
    
      //-- All that remains is to validate that our angle is between
      //   the start and the end.
      if( (degrees < startDegrees) || (degrees > endDegrees) )
      {
        return false;
      }
    
      return true;
    }
    

    Hope this helps someone.

提交回复
热议问题