You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity新输入系统中如何解决角色二次跳跃问题?

修复Unity新输入系统二次跳跃问题

问题根源分析

  1. 输入回调未正确绑定:代码中创建了PlayerControls但未将Jump Action的performed事件绑定到Jump方法,导致跳跃逻辑未按预期触发。
  2. 禁用/启用Input Action的逻辑不可靠:在FixedUpdate中频繁切换Jump Action的启用状态,会导致输入系统状态混乱,反而引发误触发。
  3. 地面检测逻辑不完整:仅依赖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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 17:21:31