TransformTweenBehaviour.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using JetBrains.Annotations;
  3. using UnityEngine;
  4. using UnityEngine.Playables;
  5. using UnityEngine.Timeline;
  6. [Serializable]
  7. public class TransformTweenBehaviour : PlayableBehaviour
  8. {
  9. public enum TweenType
  10. {
  11. Linear,
  12. Deceleration,
  13. Harmonic,
  14. Custom,
  15. }
  16. public Transform startLocation;
  17. public Transform endLocation;
  18. public bool tweenPosition = true;
  19. public bool tweenRotation = true;
  20. public TweenType tweenType;
  21. public AnimationCurve customCurve = AnimationCurve.Linear(0f, 0f, 1f, 1f);
  22. public Vector3 startingPosition;
  23. public Quaternion startingRotation = Quaternion.identity;
  24. AnimationCurve m_LinearCurve = AnimationCurve.Linear(0f, 0f, 1f, 1f);
  25. AnimationCurve m_DecelerationCurve = new AnimationCurve
  26. (
  27. new Keyframe(0f, 0f, -k_RightAngleInRads, k_RightAngleInRads),
  28. new Keyframe(1f, 1f, 0f, 0f)
  29. );
  30. AnimationCurve m_HarmonicCurve = AnimationCurve.EaseInOut(0f, 0f, 1f, 1f);
  31. const float k_RightAngleInRads = Mathf.PI * 0.5f;
  32. public override void PrepareFrame (Playable playable, FrameData info)
  33. {
  34. if (startLocation)
  35. {
  36. startingPosition = startLocation.position;
  37. startingRotation = startLocation.rotation;
  38. }
  39. }
  40. public float EvaluateCurrentCurve (float time)
  41. {
  42. if (tweenType == TweenType.Custom && !IsCustomCurveNormalised ())
  43. {
  44. Debug.LogError("Custom Curve is not normalised. Curve must start at 0,0 and end at 1,1.");
  45. return 0f;
  46. }
  47. switch (tweenType)
  48. {
  49. case TweenType.Linear:
  50. return m_LinearCurve.Evaluate (time);
  51. case TweenType.Deceleration:
  52. return m_DecelerationCurve.Evaluate (time);
  53. case TweenType.Harmonic:
  54. return m_HarmonicCurve.Evaluate (time);
  55. default:
  56. return customCurve.Evaluate (time);
  57. }
  58. }
  59. bool IsCustomCurveNormalised ()
  60. {
  61. if (!Mathf.Approximately (customCurve[0].time, 0f))
  62. return false;
  63. if (!Mathf.Approximately (customCurve[0].value, 0f))
  64. return false;
  65. if (!Mathf.Approximately (customCurve[customCurve.length - 1].time, 1f))
  66. return false;
  67. return Mathf.Approximately (customCurve[customCurve.length - 1].value, 1f);
  68. }
  69. }