就unity3d动画系统的动画曲线描绘,我在网上找到一篇文章,虽然简单,但我觉得还是比较实用的,现在分享给大家。
在Unity3D中,编辑Transform动画曲线,看不到GameObject的运动路线。我写了个脚本,挂到有动画的GameObject上,就能显示运行动画时的路线了。
效果如下:
- using UnityEngine;
- using UnityEditor;
- using System.Collections;
- public class AnimationGizmos : MonoBehaviour {
- // 曲线中的点数量
- public int Interpolations = 32;
- // 绘制路径曲线
- void OnDrawGizmos() {
- if(Interpolations > 0) {
- Gizmos.color = Color.red;
- // 获取所有的动画曲线
- AnimationClip[] clips = AnimationUtility.GetAnimationClips(gameObject);
- if (clips.Length == 0) {
- return;
- }
- for (int curveIndex = 0; curveIndex < clips.Length; curveIndex++) {
- Vector3[] points = new Vector3[Interpolations + 1];
- AnimationCurve curveX = null;
- AnimationCurve curveY = null;
- AnimationCurve curveZ = null;
- float TotalTime = 0;
- bool curveReady = false;
- AnimationClip clip = clips[curveIndex];
- AnimationClipCurveData[] curveDatas = AnimationUtility.GetAllCurves(clip, true);
- foreach (AnimationClipCurveData curveData in curveDatas) {
- if ("m_LocalPosition.x" == curveData.propertyName) {
- curveX = curveData.curve;
- TotalTime = GetMaxTime(curveData.curve, TotalTime);
- curveReady = true;
- } else if ("m_LocalPosition.y" == curveData.propertyName) {
- curveY = curveData.curve;
- TotalTime = GetMaxTime(curveData.curve, TotalTime);
- curveReady = true;
- } else if ("m_LocalPosition.z" == curveData.propertyName) {
- curveZ = curveData.curve;
- TotalTime = GetMaxTime(curveData.curve, TotalTime);
- curveReady = true;
- }
- }
- if (!curveReady) {
- Debug.LogWarning(clip.name + " 动画无位移");
- continue;
- }
- float interval = TotalTime / Interpolations;
- for (int i = 0; i <= Interpolations; i++) {
- float time = i * interval;
- Vector3 pos = transform.localPosition;
- if (curveX != null) {
- pos.x = curveX.Evaluate(time);
- }
- if (curveY != null) {
- pos.y = curveY.Evaluate(time);
- }
- if (curveZ != null) {
- pos.z = curveZ.Evaluate(time);
- }
- if (transform.parent != null) {
- pos = transform.parent.TransformPoint(pos);
- }
- points[i] = pos;
- }
- for(int i = 0; i < Interpolations;i++) {
- Gizmos.DrawLine(points[i], points[i+1]);
- }
- }
- }
- }
- private static float GetMaxTime(AnimationCurve curveX, float TotalTime) {
- foreach (Keyframe keyframe in curveX.keys) {
- if (keyframe.time > TotalTime) {
- TotalTime = keyframe.time;
- }
- }
- return TotalTime;
- }
- }