using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
public class AnimationSplitter : MonoBehaviour
{
public AnimationClip originalClip; // 要分割的原始动画剪辑
public List<int> keyFrames; // 关键帧列表
public void SplitAnimation()
{
if (originalClip == null || keyFrames == null || keyFrames.Count == 0)
{
Debug.LogError("原始动画剪辑为空或关键帧列表无效");
return;
}
float frameRate = originalClip.frameRate;
keyFrames.Sort(); // 确保关键帧列表按升序排列
List<int> segments = new List<int> { 0 }; // 添加起始帧
segments.AddRange(keyFrames);
segments.Add(Mathf.FloorToInt(originalClip.length * frameRate)); // 添加结束帧
for (int i = 0; i < segments.Count - 1; i++)
{
int startFrame = segments[i];
int endFrame = segments[i + 1];
AnimationClip newClip = new AnimationClip();
newClip.frameRate = frameRate;
foreach (var binding in AnimationUtility.GetCurveBindings(originalClip))
{
AnimationCurve curve = AnimationUtility.GetEditorCurve(originalClip, binding);
AnimationCurve newCurve = new AnimationCurve();
bool startKeyAdded = false;
bool endKeyAdded = false;
foreach (Keyframe key in curve.keys)
{
float keyTime = key.time * frameRate;
if (keyTime >= startFrame && keyTime <= endFrame)
{
newCurve.AddKey(new Keyframe(key.time - (startFrame / frameRate), key.value, key.inTangent, key.outTangent));
}
if (keyTime == startFrame)
{
startKeyAdded = true;
}
if (keyTime == endFrame)
{
endKeyAdded = true;
}
}
// 在开始帧和结束帧插入关键帧
if (!startKeyAdded)
{
float startTime = startFrame / frameRate;
float startValue = curve.Evaluate(startTime);
newCurve.AddKey(new Keyframe(0, startValue, 0, 0));
}
if (!endKeyAdded)
{
float endTime = endFrame / frameRate;
float endValue = curve.Evaluate(endTime);
newCurve.AddKey(new Keyframe((endFrame - startFrame) / frameRate, endValue, 0, 0));
}
newClip.SetCurve(binding.path, binding.type, binding.propertyName, newCurve);
}
AssetDatabase.CreateAsset(newClip, $"Assets/{originalClip.name}_Part{i + 1}.anim");
Debug.Log($"Created clip: {originalClip.name}_Part{i + 1}");
}
AssetDatabase.SaveAssets();
}
}
unity动画片段分割
最新推荐文章于 2024-08-19 22:39:17 发布