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(); _rigidbody = GetComponent(); _playerInput.onActionTriggered += OnActionTriggered; } private void OnActionTriggered(InputAction.CallbackContext ctx) { if (ctx.action.name == "Move") { var moveInput = ctx.ReadValue(); _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 o) { o(frontLeftWheel); o(frontRightWheel); o(frontLeftWheel); o(frontRightWheel); } } }