1
0

BicyclePhysics.cs 2.4 KB

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