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

Unity中使用GetButtonDown/Up无法实现按住按钮持续生效问题求助

解决按住按钮保持蹲伏效果的问题

你的问题出在**Input.GetButtonDown和Input.GetButtonUp仅在按键状态变化的瞬间触发一次**,无法持续维持蹲伏时的速度效果。要实现按住期间保持效果、松开停止,需要用Input.GetButton持续检测按钮是否处于按住状态,每帧更新对应的逻辑。

修改后的蹲伏代码

private void crouch()
{
    if (Input.GetButton("crouch"))
    {
        // 按住按钮时,每帧持续应用蹲伏速度
        float slideSpeed = targetVelocity * 0.6f;
        rb.velocity = new Vector2(slideSpeed, rb.velocity.y);
    }
    else
    {
        // 未按住按钮时,每帧恢复正常速度
        rb.velocity = new Vector2(speed, rb.velocity.y);
    }
}

关键说明

  1. 确保crouch方法在Update或FixedUpdate中每帧调用,这样才能实时检测按键状态并更新速度。
  2. 如果你的移动逻辑还有其他修改rb.velocity.x的代码,要避免冲突——比如不要在其他地方同时覆盖X轴速度,否则会抵消蹲伏的速度设置。
  3. 完整的蹲伏效果通常还需要调整碰撞体(比如缩小胶囊体高度),避免角色穿模,示例代码如下:
private CapsuleCollider capCollider;
private float originalHeight;

private void Start()
{
    capCollider = GetComponent<CapsuleCollider>();
    originalHeight = capCollider.height;
}

private void crouch()
{
    if (Input.GetButton("crouch"))
    {
        float slideSpeed = targetVelocity * 0.6f;
        rb.velocity = new Vector2(slideSpeed, rb.velocity.y);
        
        // 缩小碰撞体实现蹲伏物理效果
        capCollider.height = originalHeight * 0.5f;
        capCollider.center = new Vector3(0, originalHeight * -0.25f, 0);
    }
    else
    {
        rb.velocity = new Vector2(speed, rb.velocity.y);
        
        // 恢复碰撞体原始状态
        capCollider.height = originalHeight;
        capCollider.center = Vector3.zero;
    }
}

内容的提问来源于stack exchange,提问作者Sodatex

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 08:42:13