Skip to content

Instantly share code, notes, and snippets.

@Quickz
Created April 13, 2020 20:26
Show Gist options
  • Save Quickz/ade0c7018a6238ac11fa0754884cda11 to your computer and use it in GitHub Desktop.
Save Quickz/ade0c7018a6238ac11fa0754884cda11 to your computer and use it in GitHub Desktop.
A simple utility class for limiting rotation in Unity.
public static class RotationUtility
{
/// <param name="rotation">
/// Value of 0f to 360f.
/// Rotation that will be limitted to a certain angle.
/// </param>
public static float LimitRotation(
float rotation,
float minRotation,
float maxRotation)
{
if (minRotation > maxRotation)
{
throw new ArgumentException("Min rotation cannot exceed the max!");
}
if (rotation < 0f ||
rotation > 360f)
{
throw new ArgumentException("Rotation has to be a value in range from 0f to 360f!");
}
if (rotation > maxRotation ||
rotation < minRotation)
{
float rotationDistanceFromMaxValue = Mathf.Abs(Mathf.DeltaAngle(rotation, maxRotation));
float rotationDistanceFromMinValue = Mathf.Abs(Mathf.DeltaAngle(rotation, minRotation));
if (rotationDistanceFromMaxValue < rotationDistanceFromMinValue)
{
return maxRotation;
}
return minRotation;
}
return rotation;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment