123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- using System;
- using UnityEngine;
- using UnityEngine.Serialization;
- public class SensorBikeController : MonoBehaviour
- {
- public float maxSpeed = 40f;
- public float maxMotorTorque = 1000;
- public float leaningAngleMultiplier = 0.1f;
- public SpeedSensorConfig speedSensorConfig;
- public PolarSensorConfig polarSensorConfig;
- private BicycleController bicycleController;
- private BikeSensorData sensorData;
- private void Start()
- {
- bicycleController = GetComponent<BicycleController>();
- sensorData = BikeSensorData.Instance;
- sensorData.StartListening(polarSensorConfig: polarSensorConfig, speedSensorConfig: speedSensorConfig);
- }
- private void Update()
- {
- var speedData = sensorData.SpeedData;
- var polarData = sensorData.PolarData;
- if (speedData != null)
- {
- SetSpeed(speedData.Value);
- }
- if (polarData != null)
- {
- SetLeaningAngle(polarData.Value);
- }
- }
- private void OnDestroy()
- {
- sensorData.Dispose();
- }
- private void SetLeaningAngle(PolarSensorData polarData)
- {
- bicycleController.CurrentLeaningAngle = polarData.Acc.x * leaningAngleMultiplier;
- }
- private void SetSpeed(SpeedSensorData speedData)
- {
- var currentSpeed = bicycleController.rigidBody.velocity.magnitude;
- var speedDif = speedData.Speed - currentSpeed;
- var ratio = speedDif / maxSpeed;
- var torque = maxMotorTorque * ratio;
- if (speedDif >= .1f) // 0.36 km/h
- {
- Debug.Log($"SpeedDif = {speedDif} -> applying Torque {torque} (Ratio: {ratio})");
- bicycleController.CurrentBrakeTorque = 0;
- bicycleController.CurrentMotorTorque = torque;
- }
- else if (speedDif <= -.1f)
- {
- Debug.Log($"SpeedDif = {speedDif} -> applying brake Torque {torque} (Ratio: {ratio})");
- bicycleController.CurrentMotorTorque = 0;
- bicycleController.CurrentBrakeTorque = -torque;
- }
- else
- {
- bicycleController.CurrentMotorTorque = 0;
- bicycleController.CurrentBrakeTorque = 0;
- }
- }
- }
|