SensorBikeController.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.Serialization;
  4. [Serializable]
  5. public struct PolarRotationMapping
  6. {
  7. public float maxRight;
  8. public float center;
  9. }
  10. public class SensorBikeController : MonoBehaviour
  11. {
  12. public float maxSpeed = 40f;
  13. public float maxMotorTorque = 1000;
  14. public PolarRotationMapping polarRotationMapping;
  15. public SpeedSensorConfig speedSensorConfig;
  16. public PolarSensorConfig polarSensorConfig;
  17. public bool steer = true;
  18. public bool accelerate = true;
  19. public bool lean = true;
  20. private BicycleController bicycleController;
  21. private BikeSensorData sensorData;
  22. private float leanFactor;
  23. private async void Start()
  24. {
  25. bicycleController = GetComponent<BicycleController>();
  26. sensorData = BikeSensorData.Instance;
  27. await sensorData.StartListening(polarSensorConfig: polarSensorConfig, speedSensorConfig: speedSensorConfig);
  28. leanFactor = 90f / (polarRotationMapping.maxRight - polarRotationMapping.center);
  29. }
  30. private void Update()
  31. {
  32. var speedData = sensorData.SpeedData;
  33. var polarData = sensorData.PolarData;
  34. if (speedData != null && accelerate)
  35. {
  36. SetSpeed(speedData.Value);
  37. }
  38. if (polarData != null && lean)
  39. {
  40. SetLeaningAngle(polarData.Value);
  41. }
  42. }
  43. private void OnDestroy()
  44. {
  45. sensorData.Dispose();
  46. }
  47. private void SetLeaningAngle(PolarSensorData polarData)
  48. {
  49. //don't lean while standing / walking to bike
  50. if (bicycleController.rigidBody.velocity.magnitude > .5f)
  51. {
  52. bicycleController.CurrentLeaningAngle = (polarData.Acc.y - polarRotationMapping.center) * leanFactor;
  53. }
  54. }
  55. private void SetSpeed(SpeedSensorData speedData)
  56. {
  57. var currentSpeed = bicycleController.rigidBody.velocity.magnitude;
  58. var speedDif = speedData.Speed - currentSpeed;
  59. var ratio = speedDif / maxSpeed;
  60. var torque = maxMotorTorque * ratio;
  61. if (speedDif >= .1f) // 0.36 km/h
  62. {
  63. Debug.Log($"SpeedDif = {speedDif} -> applying Torque {torque} (Ratio: {ratio})");
  64. bicycleController.CurrentBrakeTorque = 0;
  65. bicycleController.CurrentMotorTorque = torque;
  66. }
  67. else if (speedDif <= -.1f)
  68. {
  69. Debug.Log($"SpeedDif = {speedDif} -> applying brake Torque {torque} (Ratio: {ratio})");
  70. bicycleController.CurrentMotorTorque = 0;
  71. bicycleController.CurrentBrakeTorque = -torque;
  72. }
  73. // without else the speed overshoots a bit, but is way closer to real speed
  74. /*else
  75. {
  76. bicycleController.CurrentMotorTorque = 0;
  77. bicycleController.CurrentBrakeTorque = 0;
  78. }*/
  79. }
  80. }