Equation.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #if UNITY_EDITOR
  2. using UnityEngine;
  3. namespace O3DWB
  4. {
  5. public static class Equation
  6. {
  7. #region Public Static Functions
  8. /// <summary>
  9. /// Solves a quadratic equation with the specified coefficients.
  10. /// </summary>
  11. /// <param name="a">
  12. /// The 'a' coefficient of the quadratic equation.
  13. /// </param>
  14. /// <param name="b">
  15. /// The 'b' coefficient of the quadratic equation.
  16. /// </param>
  17. /// <param name="c">
  18. /// The 'x' coefficient of the quadratic equation.
  19. /// </param>
  20. /// <param name="t1">
  21. /// If the equation can be solved, this will hold the solution with the smallest value. If
  22. /// the equation has only one solution, this will be the same as t2. If no solutions can be
  23. /// found (i.e. equation can not be solved) this will be set to 0.
  24. /// </param>
  25. /// <param name="t2">
  26. /// If the equation can be solved, this will hold the solution with the biggest value. If
  27. /// the equation has only one solution, this will be the same as t1. If no solutions can be
  28. /// found (i.e. equation can not be solved) this will be set to 0.
  29. /// </param>
  30. /// <returns>
  31. /// True if the equation can be solved and false otherwise.
  32. /// </returns>
  33. public static bool SolveQuadratic(float a, float b, float c, out float t1, out float t2)
  34. {
  35. t1 = t2 = 0.0f;
  36. // Calculate delta. If less than 0, no solutions exist.
  37. float delta = b * b - 4.0f * a * c;
  38. if (delta < 0.0f) return false;
  39. // We have at least one solution, so cache these for later use
  40. float deltaSqrt = Mathf.Sqrt(delta);
  41. float oneOver2a = 1.0f / (2.0f * a);
  42. // 2 solutions?
  43. if (delta > 0.0f)
  44. {
  45. // Calculate the solutions
  46. t1 = (-b + deltaSqrt) * oneOver2a;
  47. t2 = (-b - deltaSqrt) * oneOver2a;
  48. }
  49. else t1 = t2 = -b * oneOver2a; // Only one solution
  50. // Reorder t values to make sure that t1 is always smaller or equal to t2
  51. if (t1 > t2)
  52. {
  53. float temp = t1;
  54. t1 = t2;
  55. t2 = temp;
  56. }
  57. // At least one solution was found
  58. return true;
  59. }
  60. #endregion
  61. }
  62. }
  63. #endif