BesselPath.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. namespace Core.Utility
  4. {
  5. /// <summary>
  6. /// 贝塞尔曲线
  7. /// </summary>
  8. public class BesselPath
  9. {
  10. public List<Vector3> PosList;
  11. private List<float> _time = new List<float>();
  12. public void SetPos(List<Vector3> PosList)
  13. {
  14. this.PosList = PosList;
  15. List<float> allbs = new List<float>();
  16. float allb = 0;
  17. for (int i = 0; i < PosList.Count; i += 3)
  18. {
  19. if (i + 3 > PosList.Count)
  20. {
  21. break;
  22. }
  23. Vector3 p1 = PosList[i];
  24. Vector3 p2 = PosList[i + 1];
  25. Vector3 p3 = PosList[i + 2];
  26. float b = GetPathCount(p1, p2, p3, 100);
  27. allb += b;
  28. allbs.Add(b);
  29. }
  30. _time.Clear();
  31. float allt = 0;
  32. for (int i = 0; i < allbs.Count; i++)
  33. {
  34. float currt = allbs[i] / allb;
  35. allt+=currt;
  36. _time.Add(allt);
  37. }
  38. }
  39. private float GetPathCount(Vector3 p1, Vector3 p2, Vector3 p3, int count)
  40. {
  41. float step = 1f / count;
  42. Vector3 startPos = p1;
  43. float d = 0;
  44. for (int i = 1; i < count; i++)
  45. {
  46. float t = i * count;
  47. Vector3 a = Vector3.Lerp(p1, p2, t);
  48. Vector3 b = Vector3.Lerp(a, p3, t);
  49. d += Vector3.Distance(startPos, b);
  50. startPos = b;
  51. }
  52. return d;
  53. }
  54. public float GetPathCount(int count)
  55. {
  56. float step = 1f / count;
  57. Vector3 startPos = GetValue(0);
  58. float d = 0;
  59. for (int i = 1; i < count; i++)
  60. {
  61. Vector3 currPos = GetValue(step * i);
  62. d += Vector3.Distance(startPos, currPos);
  63. }
  64. return d;
  65. }
  66. public Vector3 GetValue(float t)
  67. {
  68. int startIndex = 0;
  69. float allt = 0;
  70. float startt = 0;
  71. for (int i = 0; i < _time.Count; i++)
  72. {
  73. if (t < _time[i])
  74. {
  75. startIndex = i * 3;
  76. allt = _time[i];
  77. if (i > 0)
  78. {
  79. allt= _time[i] - _time[i - 1];
  80. startt= _time[i - 1];
  81. }
  82. break;
  83. }
  84. }
  85. float t1 = (t - startt) / allt;
  86. if (t1 > 1)
  87. {
  88. t1 = 1;
  89. }
  90. if (t1 < 0)
  91. {
  92. t1 = 0;
  93. }
  94. Vector3 a = PosList[startIndex];
  95. Vector3 p2 = PosList[startIndex + 1];
  96. Vector3 p3 = PosList[startIndex + 2];
  97. Vector3 b = Vector3.Lerp(a, p2, t1);
  98. Vector3 c = Vector3.Lerp(b, p3, t1);
  99. return c;
  100. }
  101. }
  102. }