- Home /
How can i move a Keyframe on an Animation Curve with overwriting the key on the target time?
When i move a key (keyA) on curve, and the target time already has an other key (keyB), keyA stays at the original time. How can i move keyA to overwrite keyB? The docs on AnimationCurve.MoveKey says "This is the desired behaviour for dragging keyframes in a curve editor." But the curve editor does the complete oposite: when i move keyA to a frame with keyB, simply overwrites it. How can i do the same runtime? Do i need to remove keyB manually and insert keyA? Any hints on the best practice...? Thanks! (ps.: I don't understand, why there is not an "overwrite" parameter for MoveKey...)
Answer by Yword · 5 days ago
Hi yale3d, I think AnimationCurve.MoveKey will not overwrite existing key at the target time, so you need to remove that existing key first before moving the selected key.
Or maybe you can take a look at the following extension method, MoveKeyOverwrite.
using UnityEngine;
public class TestAnimCurve : MonoBehaviour
{
public AnimationCurve curve = new AnimationCurve(
new Keyframe(0, 0),
new Keyframe(1, 1));
private void Update()
{
if (Input.GetKeyDown(KeyCode.Z))
{
// Move key0 to time:1
int selectedKeyIndex = 0;
Keyframe selectedKey = curve.keys[selectedKeyIndex];
selectedKey.time = 1;
curve.MoveKeyOverwrite(selectedKeyIndex, selectedKey);
}
}
}
public static class AnimationCurveExtensions
{
public static void MoveKeyOverwrite(this AnimationCurve curve, int index, Keyframe key)
{
if (curve.keys != null && curve.keys.Length > 0)
{
for (int i = 0; i < curve.keys.Length; i++)
{
if (Mathf.Approximately(curve.keys[i].time, key.time))
{
curve.RemoveKey(i);
}
}
}
curve.MoveKey(index, key);
}
}
Hello! I came to the same conclusion finally, no easier way to do this, i need to remove the existing key. (My approach wasn't this clean though - very nice, thank you!) What still bothers me a bit is that if i want to achieve the same functionality as in the Curve editor, i need to store the original Curve and rebuild a temporary one with each Drag Event. Which is ok, but i don't really understand, why they stated "This is the desired behaviour for dragging keyframes in a curve editor." Actually, what they did is the oposite of desired behavior, as i see... :) Anyway, thank you for your help, i really appreciate it!