Math Programming Short: ClampAngle & Clamp Generic implementation

on

This post should be deadeasy to follow, but oh well. It’s something.

In this quick post I’ll show you guys another handy dandy Utility method to clamp angles. On top of that I’ll also show you both the float and generic implementation of the Clamp function.

Angles start again at zero when going beyond 360 degrees. (imagine a circle to visualize this). In some cases the angular number can go higher than 360, for example 450 degrees which is really just 90 degrees. You can imagine getting a super high number as an angle is problematic for some software, so we need an easy way to convert that angle to a more readable format. A function like clamp angle takes in whatever angle and gives you the same angle between -360 and 360 degrees.

 
public static class Util
{
    public static float ClampAngle(float angle, float min, float max)
    {
        do
        {
            if (angle < -360)
                angle += 360;
            if (angle > 360)
                angle -= 360;

        } while (angle < -360 || angle > 360);

        return Mathf.Clamp(angle, min, max);
    }
}

 

Pancakes right? Just for fun, because one function was a bit boring here’s the Clamp function for floats.

 

   public static float Clamp(float Value, float Min, float Max)
   {
        if (Value > Max)
            return Max;
        if (Value < Min)
            return Min;
        return Value;
    }

Again pancakes, but Mike Cabe has a cool code snippet with the same Clamp function as a generic, meaning that it can be used on almost every type (as long as that type implements the IComparable interface, which most .NET datatypes do)

 
   public static T Clamp<T>(T Value, T Max, T Min)
         where T : System.IComparable<T> {
        if (Value.CompareTo(Max) > 0)
            return Max;
        if (Value.CompareTo(Min) < 0)
            return Min;
        return Value;
    }

 

If you’re interested in Generics and Extension Methods, I’ve covered them two years ago in detal here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s