ParabolaPath.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using Fort23.Core;
  2. #if !COMBAT_SERVER
  3. using UnityEngine;
  4. #endif
  5. public class ParabolaPath : CObject
  6. {
  7. public Vector2 startPos;
  8. public Vector2 targetPos;
  9. private Vector2 posOff;
  10. private float gravity = (float)(-19);
  11. public float addH;
  12. public ParabolaPath()
  13. {
  14. }
  15. public ParabolaPath(Vector2 startPos, Vector2 targetPos)
  16. {
  17. SetPos(startPos, targetPos);
  18. }
  19. // public void SetPos(Vector2 startPos, Vector2 targetPos)
  20. // {
  21. // SetPos(new Vector2(startPos), new Vector2(targetPos));
  22. // }
  23. public void SetPos(Vector3 startPos, Vector3 targetPos)
  24. {
  25. SetPos(startPos, targetPos);
  26. }
  27. public void SetPos(Vector2 startPos, Vector2 targetPos)
  28. {
  29. this.startPos = startPos;
  30. this.targetPos = targetPos;
  31. posOff = this.targetPos - this.startPos;
  32. }
  33. public Vector2 GetPos(float t)
  34. {
  35. t = Mathf.Clamp(t, 0, 1);
  36. float h = posOff.y + posOff.magnitude / 2 + addH;
  37. float v0;
  38. float angle;
  39. float time;
  40. CalculatePathWithHeight(posOff, h, out v0, out angle, out time);
  41. return CalculatePath(v0, angle, time, t);
  42. }
  43. private Vector2 CalculatePath(float v0, float angle, float step, float t)
  44. {
  45. float v = step * t;
  46. float x = v0 * v * Mathf.Cos(angle);
  47. float y = v0 * v * Mathf.Sin(angle) - 0.5f * -gravity * Mathf.Pow(v, (float)2);
  48. return new Vector2(x, y) + startPos;
  49. }
  50. private float QuadraticEquation(float a, float b, float c, float sign)
  51. {
  52. float v = b * b - 4 * a * c;
  53. v = Mathf.Max((float)0.01f, v);
  54. return (-b + sign * Mathf.Sqrt(v)) / (2 * a);
  55. }
  56. private void CalculatePathWithHeight(Vector2 targetPos, float h, out float v0, out float angle, out float time)
  57. {
  58. h = Mathf.Max((float)0.01f, h) * 0.5f;
  59. float xt = targetPos.x;
  60. float yt = targetPos.y;
  61. float g = -gravity;
  62. float a = (-0.5f * g);
  63. float c = -yt;
  64. float b = Mathf.Sqrt(2 * g * h);
  65. float tplus = QuadraticEquation(a, b, c, (float)1);
  66. float tmin = QuadraticEquation(a, b, c, (float)(-1));
  67. time = tplus > tmin ? tplus : tmin;
  68. angle = Mathf.Atan(b * time / xt);
  69. v0 = b / Mathf.Sin(angle);
  70. }
  71. public override void ActiveObj()
  72. {
  73. }
  74. public override void DormancyObj()
  75. {
  76. }
  77. }