Created
October 13, 2021 19:04
-
-
Save sebtoun/a39ff98e36da753da97f87a594174ee1 to your computer and use it in GitHub Desktop.
Unity AnimationCurve decorator to clamp the curve like RangeAttribute is for float.
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
using UnityEngine; | |
public class ClampedCurveAttribute : PropertyAttribute | |
{ | |
public readonly float MinX; | |
public readonly float MaxX; | |
public readonly float MinY; | |
public readonly float MaxY; | |
public ClampedCurveAttribute( float minX, float maxX, float minY, float maxY ) | |
{ | |
MinX = minX; | |
MaxX = maxX; | |
MinY = minY; | |
MaxY = maxY; | |
} | |
public ClampedCurveAttribute() : this( 0, 1, 0, 1 ) | |
{ | |
} | |
} |
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
using UnityEditor; | |
using UnityEngine; | |
[ CustomPropertyDrawer( typeof( ClampedCurveAttribute ) ) ] | |
public class ClampedCurveDrawer : PropertyDrawer | |
{ | |
public override void OnGUI( Rect position, SerializedProperty property, GUIContent label ) | |
{ | |
EditorGUI.BeginChangeCheck(); | |
EditorGUI.PropertyField( position, property, label ); | |
if ( EditorGUI.EndChangeCheck() ) | |
{ | |
var attr = (ClampedCurveAttribute) attribute; | |
var curve = property.animationCurveValue; | |
ClampCurve( curve, attr.MinX, attr.MaxX, attr.MinY, attr.MaxY ); | |
property.animationCurveValue = curve; | |
} | |
} | |
public static void ClampCurve( AnimationCurve curve, float minX, float maxX, float minY, float maxY ) | |
{ | |
var keys = curve.keys; | |
for ( int i = 0; i < keys.Length; i++ ) | |
{ | |
keys[ i ].time = Mathf.Clamp( keys[ i ].time, minX, maxX ); | |
keys[ i ].value = Mathf.Clamp( keys[ i ].value, minY, maxY ); | |
} | |
keys[ 0 ].time = minX; | |
keys[ keys.Length - 1 ].time = maxX; | |
curve.keys = keys; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment