SensorBikeController.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using Controller.Bicycle;
  3. using Controller.Lean;
  4. using Sensors;
  5. using Sensors.ANT;
  6. using Sensors.Polar;
  7. using Tracking;
  8. using UnityEngine;
  9. using UnityEngine.Serialization;
  10. namespace Controller
  11. {
  12. [Serializable]
  13. public struct FrontWheelTrackerConfig
  14. {
  15. public FrontWheelTracker frontWheelTracker;
  16. public float multiplicator;
  17. public float AdjustedRotation => frontWheelTracker.SteerRotation * multiplicator;
  18. }
  19. [RequireComponent(typeof(IBicycleController))]
  20. [RequireComponent(typeof(ILeanController))]
  21. public class SensorBikeController : MonoBehaviour
  22. {
  23. public PolarRotationMapping polarRotationMapping;
  24. public SpeedSensorConfig speedSensorConfig;
  25. private ILeanController leanController;
  26. public FrontWheelTrackerConfig frontWheelTrackerConfig;
  27. public bool steer = true;
  28. public bool accelerate = true;
  29. public bool lean = true;
  30. private IBicycleController bicycleController;
  31. private BikeSensorData sensorData;
  32. private bool isFrontWheelTrackerNotNull;
  33. private void Start()
  34. {
  35. leanController = GetComponent<ILeanController>();
  36. isFrontWheelTrackerNotNull = frontWheelTrackerConfig.frontWheelTracker != null;
  37. bicycleController = GetComponent<IBicycleController>();
  38. sensorData = BikeSensorData.Instance;
  39. sensorData.StartListening(speedSensorConfig);
  40. }
  41. private void Update()
  42. {
  43. var speedData = sensorData.SpeedData;
  44. if (speedData != null && accelerate)
  45. {
  46. SetSpeed(speedData.Value);
  47. }
  48. if (isFrontWheelTrackerNotNull && steer)
  49. {
  50. SetSteer();
  51. }
  52. if (lean)
  53. {
  54. SetLeaningAngle();
  55. }
  56. }
  57. private void SetSteer()
  58. {
  59. bicycleController.CurrentSteerAngle =
  60. frontWheelTrackerConfig.AdjustedRotation;
  61. }
  62. private void OnDestroy()
  63. {
  64. sensorData?.Dispose();
  65. }
  66. private void SetLeaningAngle()
  67. {
  68. //bicycleController.CurrentLeaningAngle =
  69. bicycleController.CurrentLeaningAngle = leanController.LeanAngle;
  70. }
  71. private void SetSpeed(SpeedSensorData speedData)
  72. {
  73. bicycleController.CurrentSpeed = speedData.Speed;
  74. }
  75. }
  76. }