Unity角色跳跃异常求助:跳跃高度不稳定且下落缓慢
Unity角色跳跃异常(高度不一致+下落缓慢)问题解决
问题原因分析
- 跳跃高度不稳定:原代码用
Input.GetButton("Jump")检测跳跃输入,按住空格时每帧都会执行relativeMovement.y += jumpHeight,导致y轴速度持续累加,按住时间越长跳得越高,因此每次跳跃高度不一致。 - 下落速度缓慢:
- 接地判断条件无效:原代码判断
relativeMovementInput.y < 0,但relativeMovementInput从未设置y轴值(始终为0),导致接地时无法正确重置y轴速度。 - 跳跃初速度设置不符合物理规律:直接把
jumpHeight作为y轴速度值,既导致跳跃高度失控,也间接影响下落阶段的速度表现。
- 接地判断条件无效:原代码判断
修正后的完整代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { private CharacterController characterController; [SerializeField] float movementSpeed = 5.0f; [SerializeField] float jumpHeight = 2.0f; // 建议调整为合理数值,原10会导致跳跃过高 float gravity = -9.81f; Vector3 velocity; // 重命名变量,更符合物理含义 void Start() { characterController = GetComponent<CharacterController>(); } void Update() { HandleRotation(); HandleMovementInput(); HandleGravity(); HandleJump(); characterController.Move(velocity * Time.deltaTime); } void HandleGravity() { // 接地时重置y轴速度,确保稳定贴合地面 if (characterController.isGrounded && velocity.y < 0) { velocity.y = -2f; } // 逐帧累加重力加速度 velocity.y += gravity * Time.deltaTime; } void HandleMovementInput() { float horizontalInput = Input.GetAxis("Horizontal"); float verticalInput = Input.GetAxis("Vertical"); Vector3 moveDirection = transform.forward * verticalInput + transform.right * horizontalInput; moveDirection.Normalize(); // 斜向移动时保证速度不超标 velocity.x = moveDirection.x * movementSpeed; velocity.z = moveDirection.z * movementSpeed; } void HandleJump() { // 使用GetButtonDown确保每次跳跃仅触发一次 if (Input.GetButtonDown("Jump") && characterController.isGrounded) { // 用物理公式计算准确的跳跃初速度,保证jumpHeight为实际最高点高度 velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity); } } void HandleRotation() { transform.Rotate(Vector3.up * Input.GetAxis("Mouse X")); } }
关键修改说明
- 跳跃输入检测:替换
Input.GetButton为Input.GetButtonDown,确保单次跳跃仅触发一次速度设置,避免持续累加。 - 跳跃初速度计算:使用物理公式
Mathf.Sqrt(jumpHeight * -2 * gravity),让设置的jumpHeight精准对应角色跳跃的最高点高度,符合现实物理规律。 - 接地逻辑修正:将判断条件改为
velocity.y < 0,确保角色接地时正确重置y轴速度,避免重力异常累积。 - 斜向移动优化:添加
moveDirection.Normalize(),防止同时按下多个方向键时移动速度超过设定值。
内容的提问来源于stack exchange,提问作者Siyun Cho
相关产品推荐
相关产品推荐

