SensorBikeController.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 float centerAngle = 1000f;
  10. public SpeedSensorConfig speedSensorConfig;
  11. public PolarSensorConfig polarSensorConfig;
  12. private BicycleController bicycleController;
  13. private BikeSensorData sensorData;
  14. private void Start()
  15. {
  16. bicycleController = GetComponent<BicycleController>();
  17. sensorData = BikeSensorData.Instance;
  18. sensorData.StartListening(polarSensorConfig: polarSensorConfig, speedSensorConfig: speedSensorConfig);
  19. }
  20. private void Update()
  21. {
  22. var speedData = sensorData.SpeedData;
  23. var polarData = sensorData.PolarData;
  24. if (speedData != null)
  25. {
  26. SetSpeed(speedData.Value);
  27. }
  28. if (polarData != null)
  29. {
  30. SetLeaningAngle(polarData.Value);
  31. }
  32. }
  33. private void OnDestroy()
  34. {
  35. sensorData.Dispose();
  36. }
  37. private void SetLeaningAngle(PolarSensorData polarData)
  38. {
  39. //don't lean while standing / walking to bike
  40. if (bicycleController.rigidBody.velocity.magnitude > .5f)
  41. {
  42. bicycleController.CurrentLeaningAngle = (-polarData.Acc.y - centerAngle) * leaningAngleMultiplier;
  43. }
  44. }
  45. private void SetSpeed(SpeedSensorData speedData)
  46. {
  47. var currentSpeed = bicycleController.rigidBody.velocity.magnitude;
  48. var speedDif = speedData.Speed - currentSpeed;
  49. var ratio = speedDif / maxSpeed;
  50. var torque = maxMotorTorque * ratio;
  51. if (speedDif >= .1f) // 0.36 km/h
  52. {
  53. Debug.Log($"SpeedDif = {speedDif} -> applying Torque {torque} (Ratio: {ratio})");
  54. bicycleController.CurrentBrakeTorque = 0;
  55. bicycleController.CurrentMotorTorque = torque;
  56. }
  57. else if (speedDif <= -.1f)
  58. {
  59. Debug.Log($"SpeedDif = {speedDif} -> applying brake Torque {torque} (Ratio: {ratio})");
  60. bicycleController.CurrentMotorTorque = 0;
  61. bicycleController.CurrentBrakeTorque = -torque;
  62. }
  63. else
  64. {
  65. bicycleController.CurrentMotorTorque = 0;
  66. bicycleController.CurrentBrakeTorque = 0;
  67. }
  68. }
  69. }