From c2b26c0491886b99f422e830cd9ec1637a4ddc2e Mon Sep 17 00:00:00 2001 From: 魏曹先生 <1992414357@qq.com> Date: Sun, 1 Mar 2026 09:36:29 +0800 Subject: first --- Assets/Scripts/GamePlay/Player/ChairMovement.cs | 102 ++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 Assets/Scripts/GamePlay/Player/ChairMovement.cs (limited to 'Assets/Scripts/GamePlay/Player/ChairMovement.cs') 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(); + _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); + } + } +} -- cgit