summaryrefslogtreecommitdiff
path: root/Assets/Scripts/GamePlay/Player/ChairMovement.cs
diff options
context:
space:
mode:
Diffstat (limited to 'Assets/Scripts/GamePlay/Player/ChairMovement.cs')
-rw-r--r--Assets/Scripts/GamePlay/Player/ChairMovement.cs102
1 files changed, 102 insertions, 0 deletions
diff --git a/Assets/Scripts/GamePlay/Player/ChairMovement.cs b/Assets/Scripts/GamePlay/Player/ChairMovement.cs
new file mode 100644
index 0000000..f254c97
--- /dev/null
+++ b/Assets/Scripts/GamePlay/Player/ChairMovement.cs
@@ -0,0 +1,102 @@
+using System;
+using UnityEngine;
+using UnityEngine.InputSystem;
+
+namespace GamePlay.Player
+{
+ [RequireComponent(typeof(PlayerInput))]
+ [RequireComponent(typeof(Rigidbody))]
+ public class ChairMovement : MonoBehaviour
+ {
+ private PlayerInput _playerInput;
+ private Rigidbody _rigidbody;
+
+ private float _inputHorizontal;
+ private float _inputVertical;
+
+ public float maxMotorTorque = 400f;
+ public float maxSteerAngle = 90f;
+ public float brakeTorque = 1000f;
+
+ public WheelCollider frontLeftWheel;
+ public WheelCollider frontRightWheel;
+ public WheelCollider rearLeftWheel;
+ public WheelCollider rearRightWheel;
+
+ private void Awake()
+ {
+ _playerInput = GetComponent<PlayerInput>();
+ _rigidbody = GetComponent<Rigidbody>();
+
+ _playerInput.onActionTriggered += OnActionTriggered;
+ }
+
+ private void OnActionTriggered(InputAction.CallbackContext ctx)
+ {
+ if (ctx.action.name == "Move")
+ {
+ var moveInput = ctx.ReadValue<Vector2>();
+ _inputHorizontal = moveInput.x;
+ _inputVertical = moveInput.y;
+ }
+ }
+
+ private void FixedUpdate()
+ {
+ ApplySteering();
+ ApplyMotor();
+ ApplyBrakes();
+ }
+
+ private void ApplySteering()
+ {
+ float steer = maxSteerAngle * _inputHorizontal;
+ frontLeftWheel.steerAngle = steer;
+ frontRightWheel.steerAngle = steer;
+ }
+
+ private void ApplyMotor()
+ {
+ if (_inputVertical > 0)
+ {
+ float motor = maxMotorTorque * _inputVertical;
+ OperateWheel(w => w.motorTorque = motor);
+
+ // 释放刹车(因为在前进)
+ OperateWheel(w => w.brakeTorque = 0);
+ }
+ }
+
+ private void ApplyBrakes()
+ {
+ if (_inputVertical < 0)
+ {
+ if (_rigidbody.linearVelocity.z > 0.1f)
+ {
+ float brake = brakeTorque * Mathf.Abs(_inputVertical);
+ OperateWheel(w => w.brakeTorque = brake);
+ OperateWheel(w => w.motorTorque = 0);
+ }
+ else
+ {
+ OperateWheel(w => w.brakeTorque = 0);
+ OperateWheel(w => w.motorTorque = maxMotorTorque * _inputVertical);
+ }
+ }
+ else if (Mathf.Abs(_inputVertical) < 0.1f)
+ {
+ float parkingBrake = 10f;
+ OperateWheel(w => w.brakeTorque = parkingBrake);
+ OperateWheel(w => w.motorTorque = 0);
+ }
+ }
+
+ private void OperateWheel(Action<WheelCollider> o)
+ {
+ o(frontLeftWheel);
+ o(frontRightWheel);
+ o(frontLeftWheel);
+ o(frontRightWheel);
+ }
+ }
+}