如何确保在C#中未按下按钮?

问题描述 投票:-1回答:1

所以我目前正在用C#制作游戏,我通过按住左移键增加了冲刺的能力,但问题是我不希望玩家在蹲伏时能够冲刺,而这可能发生在只要同时按住左移键和左控制键即可。我已经尝试过“ GetButtonUp”和“ GetButtonDown”,但是它们根本不起作用。这是我当前遇到问题的Sprint脚本:

public class AdvancedMovement : MonoBehaviour
{
    //Variables;
    PlayerMovement basicMovementScript;
    public float speedBoost = 10f;

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

    // Update is called once per frame
    void Update()
    {

        if (Input.GetKeyDown(KeyCode.LeftShift))
            beginSprint();
        else if (Input.GetKeyUp(KeyCode.LeftShift))
            endSprint();
    }

    private void beginSprint()
    {
        basicMovementScript.speed += speedBoost;
    }

    private void endSprint()
    {
        basicMovementScript.speed -= speedBoost;
    }
}

非常感谢您的帮助。谢谢。

c# button input
1个回答
0
投票

[Input.GetKeyDownInput.GetKeyUp仅被调用一次,那是在执行动作并渲染下一帧时。

如果由于性能或调试原因而跳过特定帧,可能会导致意外行为。在您的情况下,可能会转换为调用endSprint而没有检测到Input.GetKeyDown(KeyCode.LeftShift)作为示例。

我建议您改用Input.GetKey,每次按住该键时都会在每次更新时调用它。

根据您的情况,您可以这样做:

if (Input.GetKeyDown(KeyCode.LeftShift) && !Input.GetKey(KeyCode.Leftcontrol)),将确保不按住向左Ctrl键。

我在类似情况下也将执行的操作,而不是使用Input.GetKeyDown(KeyCode.LeftShift),我将创建一个标志_isSprinting并以类似于以下方式的方式使用它:

void Update()
{

    if (!_isSprinting && Input.GetKey(KeyCode.LeftShift) && !Input.GetKey(KeyCode.Leftcontrol)))
    {
        beginSprint();

        _isSprinting = true;
    }

    if (_isSprinting && !Input.GetKey(KeyCode.LeftShift))
    {
        endSprint();

        _isSprinting = false;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.