RbBicycleController.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 => currentSteerAngle = Mathf.Clamp(value, -maxSteeringAngle, maxSteeringAngle);
  26. }
  27. public float CurrentLeaningAngle
  28. {
  29. get => currentLeaningAngle;
  30. set
  31. {
  32. //don't lean while standing / walking to bike
  33. if (rigidBody.velocity.magnitude < .5f) return;
  34. currentLeaningAngle = Mathf.Clamp(value, -maxLeaningAngle, maxLeaningAngle);
  35. }
  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. ApplySteerAngleAndRotation();
  53. }
  54. private void ApplyVelocity()
  55. {
  56. var targetVelocity = new Vector3(0, 0, CurrentSpeed);
  57. targetVelocity = rbTransform.TransformDirection(targetVelocity);
  58. var velocityChange = targetVelocity - rigidBody.velocity;
  59. velocityChange.y = 0;
  60. rigidBody.AddForce(velocityChange, ForceMode.VelocityChange);
  61. }
  62. private void ApplySteerAngleAndRotation()
  63. {
  64. //don't lean and rotate when veeeeeery sloooow/standing. Otherwise bike will rotate already
  65. if (CurrentSpeed < 0.3f) //ca 1 km/h
  66. {
  67. CurrentSteerAngle = 0;
  68. CurrentLeaningAngle = 0;
  69. }
  70. if (controllerMode == BicycleControllerMode.Independent)
  71. {
  72. var r = rbTransform.localRotation.eulerAngles;
  73. rbTransform.localRotation =
  74. Quaternion.Euler(r + new Vector3(0, CurrentSteerAngle, -CurrentLeaningAngle) * Time.fixedDeltaTime);
  75. }
  76. else if (controllerMode == BicycleControllerMode.LeaningAngleDependentOnSteerAngle)
  77. {
  78. //TODO
  79. }
  80. }
  81. }
  82. }