Created
April 13, 2020 20:26
-
-
Save Quickz/ade0c7018a6238ac11fa0754884cda11 to your computer and use it in GitHub Desktop.
A simple utility class for limiting rotation in Unity.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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