unity3d动画系统的动画曲线描绘,我在网上找到一篇文章,虽然简单,但我觉得还是比较实用的,现在分享给大家。

在Unity3D中,编辑Transform动画曲线,看不到GameObject的运动路线。我写了个脚本,挂到有动画的GameObject上,就能显示运行动画时的路线了。

效果如下:

unity3d动画系统的动画曲线描绘
  1. using UnityEngine;
  2. using UnityEditor;
  3. using System.Collections;
  4. public class AnimationGizmos : MonoBehaviour {
  5. // 曲线中的点数量
  6. public int Interpolations = 32;
  7. // 绘制路径曲线
  8. void OnDrawGizmos() {
  9. if(Interpolations > 0) {
  10. Gizmos.color = Color.red;
  11. // 获取所有的动画曲线
  12. AnimationClip[] clips = AnimationUtility.GetAnimationClips(gameObject);
  13. if (clips.Length == 0) {
  14. return;
  15. }
  16. for (int curveIndex = 0; curveIndex < clips.Length; curveIndex++) {
  17. Vector3[] points = new Vector3[Interpolations + 1];
  18. AnimationCurve curveX = null;
  19. AnimationCurve curveY = null;
  20. AnimationCurve curveZ = null;
  21. float TotalTime = 0;
  22. bool curveReady = false;
  23. AnimationClip clip = clips[curveIndex];
  24. AnimationClipCurveData[] curveDatas = AnimationUtility.GetAllCurves(clip, true);
  25. foreach (AnimationClipCurveData curveData in curveDatas) {
  26. if ("m_LocalPosition.x" == curveData.propertyName) {
  27. curveX = curveData.curve;
  28. TotalTime = GetMaxTime(curveData.curve, TotalTime);
  29. curveReady = true;
  30. } else if ("m_LocalPosition.y" == curveData.propertyName) {
  31. curveY = curveData.curve;
  32. TotalTime = GetMaxTime(curveData.curve, TotalTime);
  33. curveReady = true;
  34. } else if ("m_LocalPosition.z" == curveData.propertyName) {
  35. curveZ = curveData.curve;
  36. TotalTime = GetMaxTime(curveData.curve, TotalTime);
  37. curveReady = true;
  38. }
  39. }
  40. if (!curveReady) {
  41. Debug.LogWarning(clip.name + " 动画无位移");
  42. continue;
  43. }
  44. float interval = TotalTime / Interpolations;
  45. for (int i = 0; i <= Interpolations; i++) {
  46. float time = i * interval;
  47. Vector3 pos = transform.localPosition;
  48. if (curveX != null) {
  49. pos.x = curveX.Evaluate(time);
  50. }
  51. if (curveY != null) {
  52. pos.y = curveY.Evaluate(time);
  53. }
  54. if (curveZ != null) {
  55. pos.z = curveZ.Evaluate(time);
  56. }
  57. if (transform.parent != null) {
  58. pos = transform.parent.TransformPoint(pos);
  59. }
  60. points[i] = pos;
  61. }
  62. for(int i = 0; i < Interpolations;i++) {
  63. Gizmos.DrawLine(points[i], points[i+1]);
  64. }
  65. }
  66. }
  67. }
  68. private static float GetMaxTime(AnimationCurve curveX, float TotalTime) {
  69. foreach (Keyframe keyframe in curveX.keys) {
  70. if (keyframe.time > TotalTime) {
  71. TotalTime = keyframe.time;
  72. }
  73. }
  74. return TotalTime;
  75. }
  76. }