TweenPath.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. public class TweenPath : Tweener
  5. {
  6. public Transform target;
  7. public Vector3[] path;
  8. public bool isWorld = false;
  9. private float from = 0f;
  10. private float to = 1f;
  11. private List<Vector3> pathPoints = new List<Vector3>();
  12. private float mValue;
  13. public float value {
  14. get {
  15. return mValue;
  16. }
  17. set {
  18. mValue = value;
  19. if (target != null)
  20. {
  21. if (isWorld)
  22. {
  23. target.position = GetCRSPoint(mValue);
  24. }
  25. else
  26. {
  27. target.localPosition = GetCRSPoint(mValue);
  28. }
  29. }
  30. }
  31. }
  32. protected override void Start()
  33. {
  34. pathPoints = BuildCRSplinePath(new List<Vector3>(path));
  35. if (target == null)
  36. {
  37. target = transform;
  38. }
  39. }
  40. protected override void OnUpdate(float factor, bool isFinished)
  41. {
  42. float t = from + factor * (to - from);
  43. value = Mathf.Clamp01(t);
  44. }
  45. public List<Vector3> BuildCRSplinePath(List<Vector3> pts)
  46. {
  47. List<Vector3> path = new List<Vector3>(pts);
  48. if (pts[0] == pts[pts.Count - 1])
  49. {
  50. path.Insert(0, pts[pts.Count - 2]);
  51. path.Add(pts[1]);
  52. }
  53. else
  54. {
  55. path.Insert(0, pts[0] + (pts[0] - pts[1]));
  56. path.Add(pts[pts.Count - 1] + (pts[pts.Count - 1] - pts[pts.Count - 2]));
  57. }
  58. return path;
  59. }
  60. public Vector3 CRSpline(List<Vector3> pts, float t)
  61. {
  62. int numSections = pts.Count - 3;
  63. int currPt = Mathf.Min(Mathf.FloorToInt(t * (float)numSections), numSections - 1);
  64. float u = t * (float)numSections - (float)currPt;
  65. Vector3 a = pts[currPt];
  66. Vector3 b = pts[currPt + 1];
  67. Vector3 c = pts[currPt + 2];
  68. Vector3 d = pts[currPt + 3];
  69. return 0.5f * (
  70. (-a + 3f * b - 3f * c + d) * (u * u * u)
  71. + (2f * a - 5f * b + 4f * c - d) * (u * u)
  72. + (-a + c) * u
  73. + 2f * b
  74. );
  75. }
  76. public Vector3 GetCRSPoint(float t)
  77. {
  78. return CRSpline(pathPoints, t);
  79. }
  80. public void OnDrawGizmos()
  81. {
  82. if (path == null || path.Length < 2)
  83. {
  84. return;
  85. }
  86. int i = 0, count = path.Length;
  87. Gizmos.color = Color.cyan;
  88. if (count > 1)
  89. {
  90. while (i < count)
  91. {
  92. if (i < count - 1)
  93. {
  94. Gizmos.DrawLine(path[i], path[i + 1]);
  95. }
  96. i++;
  97. }
  98. }
  99. //Gizmos.color = Color.yellow;
  100. for (i = 0, count = path.Length; i < path.Length; i++)
  101. {
  102. Gizmos.DrawIcon(path[i], "AvatarInspector/DotFrame");
  103. }
  104. }
  105. }