RbBicycleController.cs 2.9 KB

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