Unity:在更新中无法可靠地检测到Input.GetButtonDown?

Kyl*_*lee 3 unity-game-engine

我有一个玩家脚本,我正在尝试实现跳转。问题是它Input.GetButtonDown("Jump")在更新中并没有持续触发。我知道这是在固定更新中的问题。这是我的代码。

注意:我戴上[SerializeField]pressingJump这样holdingJump我就可以看到发生了什么。pressingJump不一致(如预期)但holdingJump工作完美。

using UnityEngine;

public class Player : MonoBehaviour
{
    public float fallMultiplier = 15f;
    public float lowJumpMultiplier = 10f;
    public float walkSpeed = 20f;
    public float jumpSpeed = 15f;

    public bool canMove = true;
    public bool canJump = true;
    
    Rigidbody rb;

    float horizontalInput;
    bool doJump;
    bool pressingJump;
    bool holdingJump;
    
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        CaputureInput();
    }

    void CaputureInput()
    {
        if (canMove) {
            horizontalInput = Input.GetAxisRaw("Horizontal");
        }
        

        pressingJump = Input.GetButtonDown ("Jump");
        doJump = pressingJump && canJump;
        holdingJump = Input.GetButton ("Jump") && canJump;
    }
    
    void FixedUpdate()
    {
        Move();
        Jump();
    }
    
    void Move()
    {
        rb.velocity = new Vector2(horizontalInput * walkSpeed, rb.velocity.y);
    }
    
    void Jump()
    {
        if (doJump) {
            rb.velocity += Vector3.up * jumpSpeed;
            doJump = false;
        }

        if (rb.velocity.y < 0) {
            rb.velocity += Vector3.up * Physics.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
        } else if (rb.velocity.y > 0 && !holdingJump) {
            rb.velocity += Vector3.up * Physics.gravity.y * (lowJumpMultiplier - 1) * Time.deltaTime;
        }        
    }
}
Run Code Online (Sandbox Code Playgroud)

Kyl*_*lee 5

好的在这里找到了解决方案: https: //www.reddit.com/r/Unity3D/comments/9nr2sd/inputgetbuttondown_and_getbuttonup_dont_work/e7ogta1 ?utm_source=share&utm_medium=web2x

这就是我遇到的问题。

编辑:评论指出链接可能不被接受。这是链接中的相关内容。它指出了问题发生的原因以及解决方法。

使用您编写的代码最终得到的结果与在FixedUpdate 中进行输入检查时基本相同。

这是因为 Update 在每个 FixUpdate 之间运行多次。现在,在这种情况下,这对您的代码意味着是的,您确实在更新期间捕获了 ButtonDown("Jump") 的状态,但请考虑一下:如果另一个更新发生在固定更新之前,button_down/up_jump 会发生什么?GetButtonDown 和 GetButtonUp 都是仅对于发生按键/释放的一帧为 true 的函数。换句话说,这正在发生

更新运行 -> Button_down_jump 为 false

用户按下“跳转”。

更新运行 -> Button_down_jump 为 true

更新运行 -> Button_down_jump 为 false

由于 Button_down_jump 的状态,FixedUpdate 运行 -> 没有任何反应

现在,您实际上遇到过一些情况,您在正确的时间按下/取消按下“跳转”以设法打印任何内容。仅当发生以下情况时才会发生这种情况:

用户取消/按下“跳转”

更新运行(一次)

固定更新运行

你真正想做的是这样的:

无效更新(){如果(Input.GetButtonDown(“跳转”)){button_down_jump = true; //这捕获一帧之外的布尔值的状态,因为它仅在输入事件发生时设置 } if(Input.GetButtonUp("jump")) { button_up_jump = true; } }