RbBicycleController.cs 2.8 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 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. 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
  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 = Quaternion.Euler(r + new Vector3(0, CurrentSteerAngle, -CurrentLeaningAngle) * Time.fixedDeltaTime);
  74. }else if (controllerMode == BicycleControllerMode.LeaningAngleDependentOnSteerAngle)
  75. {
  76. //TODO
  77. }
  78. }
  79. }
  80. }