Clamping angle for any range

I need a function to clamp an angle (in degrees) into an arbitrary range [min,max]. Here are some examples: Angle Range Examples

Colored areas represent the actual range of angles.

  • In image # 1, ang should be clamped to max (-90)
  • In image # 2, ang should be clamped to mines (135)
  • In image No. 3, ang should be clamped to mines (135)

This is what I have so far:

static float clamp_angle(float ang,float min,float max)
{
    ang = normalize_angle(ang); // normalize_angle transforms angle into [-180,180) range
    min = normalize_angle(min);
    max = normalize_angle(max);
    if(angle_in_range(ang,min,max) == false)
    {
        if(abs(get_angle_difference(ang,min)) < abs(get_angle_difference(ang,max))
            ang = min; // Clamp to min if we're closer to min than max
        else
            ang = max;
    }
    return ang;
}

I miss the function angle_in_range( trueif the angle is within the range, otherwise false).
What would be the easiest way to determine if an angle is within a range or not?

+4
source share
2 answers

, ang 0, min max [-180; 180). , :

float clamp_angle(const float ang, const float min, const float max)
{
    float n_min = normalize180(min-ang);
    float n_max = normalize180(max-ang);

    if (n_min <= 0 && n_max >= 0)
    {
        return ang;
    }
    if (abs(n_min) < abs(n_max))
        return min;
    return max;
}

Live On Coliru

+2

, . min max cw- - dist (min, max) = (max-min) mod N , . dist (min, A) + dist (A, max) = dist (min, max). A, min max: dist (min, A) = (A - min) modN dist (A, max) = (max-A) modN. A , N + dist (min, max), dist (min, max)

N = 360 [0,360)

: (-x) modX undefined, -x , . (-x + X) modX, x [0, X)

0

Source: https://habr.com/ru/post/1669811/


All Articles