Unity新输入系统中如何解决角色二次跳跃问题?
修复Unity新输入系统二次跳跃问题
问题根源分析
- 输入回调未正确绑定:代码中创建了
PlayerControls但未将Jump Action的performed事件绑定到Jump方法,导致跳跃逻辑未按预期触发。 - 禁用/启用Input Action的逻辑不可靠:在
FixedUpdate中频繁切换Jump Action的启用状态,会导致输入系统状态混乱,反而引发误触发。 - 地面检测逻辑不完整:仅依赖
OnCollisionStay设置isGrounded,未处理角色意外离开地面(比如掉落)时的状态重置。
修复步骤
1. 正确绑定输入回调
在OnEnable中添加Jump事件绑定,OnDisable中解绑避免内存泄漏:
void OnEnable() { inputActions = new PlayerControls(); inputActions.Enable(); // 绑定Jump的performed事件到Jump方法 inputActions.PlayerActions.Jump.performed += Jump; } void OnDisable() { // 先解绑事件再禁用输入 inputActions.PlayerActions.Jump.performed -= Jump; inputActions.Disable(); }
2. 移除不可靠的DisableJumpAction逻辑
直接删除DisableJumpAction方法以及FixedUpdate中对它的调用,转而在Jump回调中严格判断isGrounded,这比禁用Action更稳定。
3. 完善地面检测逻辑
添加OnCollisionExit方法,确保角色离开地面时isGrounded被正确重置:
public void OnCollisionExit(Collision collision) { if (collision.gameObject.tag == "Ground") { isGrounded = false; } }
4. 保留核心跳跃逻辑
确保只有角色接地时才响应跳跃输入:
public void Jump(InputAction.CallbackContext context) { if (context.performed && isGrounded) { playerRigidbody.AddForce(Vector3.up * JumpPower, ForceMode.Impulse); isGrounded = false; } }
完整修复后的代码
Rigidbody playerRigidbody; PlayerControls inputActions; bool isGrounded; // 补充你未定义的公开变量 public float playerVelocity; public float rotationPower; public float JumpPower; void OnEnable() { inputActions = new PlayerControls(); inputActions.Enable(); inputActions.PlayerActions.Jump.performed += Jump; } void OnDisable() { inputActions.PlayerActions.Jump.performed -= Jump; inputActions.Disable(); } void Start() { playerRigidbody = GetComponent<Rigidbody>(); } void FixedUpdate() { Accleration(); float steerValue = inputActions.PlayerActions.Steer.ReadValue<float>(); transform.Rotate(Vector3.up * steerValue * rotationPower * Time.deltaTime); Debug.Log("isGrounded:" + isGrounded); } void Accleration() { playerRigidbody.AddRelativeForce(Vector3.forward * playerVelocity); } public void Jump(InputAction.CallbackContext context) { if (context.performed && isGrounded) { playerRigidbody.AddForce(Vector3.up * JumpPower, ForceMode.Impulse); isGrounded = false; } } public void OnCollisionStay(Collision collision) { if (collision.gameObject.tag == "Ground") { isGrounded = true; } } public void OnCollisionExit(Collision collision) { if (collision.gameObject.tag == "Ground") { isGrounded = false; } }
额外注意事项
- 确保
PlayerControls输入资产中,Jump Action的类型为Button,触发方式设为Press。 - 检查地面对象的
Tag确实是Ground,角色Rigidbody组件已开启重力。
内容的提问来源于stack exchange,提问作者Unity Enjoyer
相关产品推荐
相关产品推荐

