RbBicycleController.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using UnityEngine;
  3. namespace Controller.Bicycle
  4. {
  5. public class RbBicycleController : BicycleControllerBaseBehaviour, IBicycleController
  6. {
  7. #region Variables
  8. private Transform rbTransform;
  9. private float currentSteerAngle;
  10. private float currentLeaningAngle;
  11. private float currentSpeed;
  12. public BicycleControllerMode ControllerMode
  13. {
  14. get => controllerMode;
  15. set => controllerMode = value;
  16. }
  17. public float CurrentSpeed
  18. {
  19. get => currentSpeed;
  20. set => currentSpeed = Mathf.Clamp(value, 0, maxSpeed);
  21. }
  22. public float CurrentSteerAngle
  23. {
  24. get => currentSteerAngle;
  25. set
  26. {
  27. //don't lean while standing / walking to bike
  28. if (rigidBody.velocity.magnitude < .5f) return;
  29. currentSteerAngle = Mathf.Clamp(value, -maxSteeringAngle, maxSteeringAngle);
  30. }
  31. }
  32. public float CurrentLeaningAngle
  33. {
  34. get => currentLeaningAngle;
  35. set => currentLeaningAngle = Mathf.Clamp(value, -maxLeaningAngle, maxLeaningAngle);
  36. }
  37. public Vector3 RigidBodyVelocity => rigidBody.velocity;
  38. #endregion
  39. private void Awake()
  40. {
  41. rbTransform = rigidBody.transform;
  42. rigidBody.freezeRotation = true;
  43. rigidBody.centerOfMass = centerOfMass.position;
  44. }
  45. private void Update()
  46. {
  47. throw new NotImplementedException();
  48. }
  49. private void FixedUpdate()
  50. {
  51. ApplyVelocity();
  52. }
  53. private void ApplyVelocity()
  54. {
  55. var targetVelocity = new Vector3(CalculateVelocityX(), 0, CurrentSpeed);
  56. targetVelocity = rbTransform.TransformDirection(targetVelocity);
  57. var velocityChange = targetVelocity - rigidBody.velocity;
  58. velocityChange.y = 0;
  59. rigidBody.AddForce(velocityChange, ForceMode.VelocityChange);
  60. }
  61. private float CalculateVelocityX()
  62. {
  63. var previousRotation = rbTransform.localRotation.eulerAngles;
  64. rbTransform.localRotation =
  65. Quaternion.Euler(previousRotation + new Vector3(0, CurrentSteerAngle, 0) * Time.fixedDeltaTime);
  66. return 0;
  67. //return CurrentSteerAngle/4; //TODO: something a bit smarter
  68. }
  69. private void ApplyLeaningAngle()
  70. {
  71. }
  72. }
  73. }