BicyclePhysics.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using UnityEngine;
  3. public class BicyclePhysics
  4. {
  5. private const float K_A = 0.5f; //wind resistance coefficient
  6. private const float A = 0.6f; //frontal area bike + rider; m2
  7. private const float D = 1.226f; //air density; kg/m3
  8. /// <summary>
  9. /// Returns a speed in m/s for a bike riding a gradient with the same power it would be ridden in the flat with the input speed.
  10. /// Using formula from http://www.sportsci.org/jour/9804/dps.html. Assuming v=s and neglecting rolling resistance
  11. /// The speed is calculated by solving k_aAs_1^3d = k_aAs_2^3d + giMs_2 for s_2
  12. /// </summary>
  13. /// <param name="speedFlat">Speed the bike would have in flat terrain</param>
  14. /// <param name="systemMass">Mass of bike + rider</param>
  15. /// <param name="gradient">gradient in vertical meters gained per meter travelled forward</param>
  16. /// <returns></returns>
  17. public static float SpeedAtGradientForSpeedAtFlat(float speedFlat, float systemMass, float gradient)
  18. {
  19. var g = -Physics.gravity.y;
  20. const float k = K_A * A * D;
  21. var b = g * gradient * systemMass;
  22. float result;
  23. if (gradient < -0.01f) // 1 percent
  24. {
  25. result = 2 * Mathf.Sqrt(-b / (3 * k)) *
  26. Mathf.Cos(
  27. Mathf.Acos(3 * Mathf.Sqrt(-3 * k / b) * k * speedFlat
  28. / (2 * b))
  29. / 3);
  30. }
  31. else
  32. {
  33. var sqrtTerm = Mathf.Sqrt(
  34. Mathf.Pow(b, 3f)
  35. /
  36. (27f * Mathf.Pow(k, 3f))
  37. +
  38. Mathf.Pow(speedFlat, 6f)
  39. /
  40. 4f
  41. );
  42. var secondTerm = Mathf.Pow(speedFlat, 3f) / 2f;
  43. result = Qbrt(sqrtTerm + secondTerm) + Qbrt(-sqrtTerm + secondTerm);
  44. }
  45. if (float.IsNaN(result))
  46. {
  47. Debug.LogWarning(
  48. $"BicyclePhysics: result is NaN for k = {k} and b = {b} (gradient = {gradient}, mass = {systemMass})");
  49. return speedFlat;
  50. }
  51. return result;
  52. }
  53. private static float Qbrt(float x) => x < 0 ? -Mathf.Pow(-x, 1f / 3f) : Mathf.Pow(x, 1f / 3f);
  54. }