Skip to content

Instantly share code, notes, and snippets.

@rodrigod89
Created July 28, 2016 14:48
Show Gist options
  • Save rodrigod89/a132e6a180f93b9f1b119f85a5438e6e to your computer and use it in GitHub Desktop.
Save rodrigod89/a132e6a180f93b9f1b119f85a5438e6e to your computer and use it in GitHub Desktop.
Animation Clip scaler
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
/// <summary>
/// Made by Rodrigo Diaz
/// http://www.goldenfrogstudios.com/
/// This code is licensed under MIT license
///
/// Make sure to add this class under a folder named "Editor" in the Unity Project
/// </summary>
public class AnimationClipScalerWindow : EditorWindow
{
private float scale;
private AnimationClip clip;
private bool tangentScale;
// Add menu item named "My Window" to the Window menu
[MenuItem("Window/Animation Clip Scaler")]
public static void ShowWindow()
{
//Show existing window instance. If one doesn't exist, make one.
EditorWindow.GetWindow(typeof(AnimationClipScalerWindow));
}
void OnGUI()
{
GUILayout.Label("Clip", EditorStyles.boldLabel);
clip = (AnimationClip)EditorGUILayout.ObjectField(clip, typeof(AnimationClip), false);
tangentScale = GUILayout.Toggle(tangentScale, "Scale tangents");
scale = EditorGUILayout.FloatField("Scale", scale);
GUI.enabled = clip != null;
if (GUILayout.Button("Scale"))
{
Undo.RecordObject(clip, "Animation scaled");
ScaleAudioClip();
}
GUI.enabled = true;
}
void ScaleAudioClip()
{
EditorCurveBinding[] data = AnimationUtility.GetCurveBindings(clip);
foreach (EditorCurveBinding b in data)
{
AnimationCurve curve = AnimationUtility.GetEditorCurve(clip, b);
List<Keyframe> keys = new List<Keyframe>();
AnimationCurve newCurve = new AnimationCurve();
foreach (Keyframe oldKey in curve.keys)
{
Keyframe key = oldKey;
key.time *= scale;
if (tangentScale)
{
key.inTangent = ScaleTangent(key.inTangent);
key.outTangent = ScaleTangent(key.outTangent);
}
newCurve.AddKey(key);
}
AnimationUtility.SetEditorCurve(clip, b, newCurve);
}
}
// Calculates new tangent based on the time offset
private float ScaleTangent(float tangent)
{
float x = Mathf.Cos(tangent) * scale;
float y = Mathf.Sin(tangent);
return Mathf.Atan2(y, x);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment