SensorBikeController.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.Serialization;
  4. public class SensorBikeController : MonoBehaviour
  5. {
  6. public float maxSpeed = 40f;
  7. public float maxMotorTorque = 1000;
  8. public float leaningAngleMultiplier = 0.1f;
  9. public SpeedSensorConfig speedSensorConfig;
  10. public PolarSensorConfig polarSensorConfig;
  11. private BicycleController bicycleController;
  12. private BikeSensorData sensorData;
  13. private void Start()
  14. {
  15. bicycleController = GetComponent<BicycleController>();
  16. sensorData = BikeSensorData.Instance;
  17. sensorData.StartListening(polarSensorConfig: polarSensorConfig, speedSensorConfig: speedSensorConfig);
  18. }
  19. private void Update()
  20. {
  21. var speedData = sensorData.SpeedData;
  22. var polarData = sensorData.PolarData;
  23. if (speedData != null)
  24. {
  25. SetSpeed(speedData.Value);
  26. }
  27. if (polarData != null)
  28. {
  29. SetLeaningAngle(polarData.Value);
  30. }
  31. }
  32. private void OnDestroy()
  33. {
  34. sensorData.Dispose();
  35. }
  36. private void SetLeaningAngle(PolarSensorData polarData)
  37. {
  38. bicycleController.CurrentLeaningAngle = polarData.Acc.x * leaningAngleMultiplier;
  39. }
  40. private void SetSpeed(SpeedSensorData speedData)
  41. {
  42. var currentSpeed = bicycleController.rigidBody.velocity.magnitude;
  43. var speedDif = speedData.Speed - currentSpeed;
  44. var ratio = speedDif / maxSpeed;
  45. var torque = maxMotorTorque * ratio;
  46. if (speedDif >= .1f) // 0.36 km/h
  47. {
  48. Debug.Log($"SpeedDif = {speedDif} -> applying Torque {torque} (Ratio: {ratio})");
  49. bicycleController.CurrentBrakeTorque = 0;
  50. bicycleController.CurrentMotorTorque = torque;
  51. }
  52. else if (speedDif <= -.1f)
  53. {
  54. Debug.Log($"SpeedDif = {speedDif} -> applying brake Torque {torque} (Ratio: {ratio})");
  55. bicycleController.CurrentMotorTorque = 0;
  56. bicycleController.CurrentBrakeTorque = -torque;
  57. }
  58. else
  59. {
  60. bicycleController.CurrentMotorTorque = 0;
  61. bicycleController.CurrentBrakeTorque = 0;
  62. }
  63. }
  64. }