簡體   English   中英

Unity Input.GetKeyDown() 事件經常錯過

[英]Unity Input.GetKeyDown() event frequently missed

我正在做一個測試項目,以在 Unity 中試驗剛體。 我從事水平運動和跳躍動作,但我有一個問題。 Input.GetKeyDown()似乎大部分時間都沒有捕捉到我的按鍵事件。 我嘗試查看可能的解決方案,這些解決方案建議在Update()中捕獲關鍵輸入,並與與FixedUpdate()的 Rigidbody 交互相對應。 當我嘗試這個時,我幾乎沒有看到任何改進。 這是我現在正在處理的腳本:

public class PlayerScript : MonoBehaviour
{
    [SerializeField] private float jumpConstant = 5.0f;
    [SerializeField] private int walkSpeed = 10;
    private bool jumpDown;
    private float horizontalInput;
    private Rigidbody rbComponent;

    // Start is called before the first frame update
    void Start()
    {
        rbComponent = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        CheckIfJumpKeyPressed();
        GetHorizontalInput();
    }

    void FixedUpdate()
    {
        JumpIfKeyPressed();
        MoveHorizontal();
    }

    void CheckIfJumpKeyPressed()
    {
        jumpDown = Input.GetKeyDown(KeyCode.Space);
    }

    void JumpIfKeyPressed()
    {
        if (jumpDown)
        {
            jumpDown = false;
            rbComponent.AddForce(Vector3.up * jumpConstant, ForceMode.VelocityChange);
            Debug.Log("Jumped!");
        }
    }

    void GetHorizontalInput()
    {
        horizontalInput = Input.GetAxis("Horizontal");
    }

    void MoveHorizontal()
    {
        rbComponent.velocity = new Vector3(horizontalInput * walkSpeed, rbComponent.velocity.y, 0);
    }
}

先感謝您。

如果在您的輸入和物理幀之間出現額外的幀,您將覆蓋您的輸入。 您應該確保缺少輸入不會覆蓋檢測到的輸入:

void CheckIfJumpKeyPressed()
{
    jumpDown |= Input.GetKeyDown(KeyCode.Space);
}

或者,等效地:

void CheckIfJumpKeyPressed()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        jumpDown = true;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM