一旦按下键,Xna的KeyboardState.IsKeyDown()就会卡住

时间:2016-06-06 20:21:13

标签: c# xna

在循环(var enterKey = Keyboard.GetState().IsKeyDown(Keys.Enter);)中运行以下代码时,即使在我释放密钥后,按下回车键也会返回true。

关于我做错什么的任何想法?

3 个答案:

答案 0 :(得分:2)

尝试这样检查:

KeyboardState newState;
public void Update(...)
{
    newState = Keyboard.GetState();
    if(newState.IsKeyDown(Keys.Enter))
    {
        *do what you want here*
    }
}

这样,在每次更新时,您都在更新当前键盘状态(按下了哪些键),因此您可以检查每个帧中的不同按键。

修改
你可能想要检查一次点击,所以不是问2个问题,而是一个"奖金"你的问题。代码类似:

KeyboardState newState, oldState;
public void Update(...)
{
    //gets keyboard state for this single frame
    newState = Keyboard.GetState();

    //checks if enter is down
    if(newState.IsKeyDown(Keys.Enter))
    {
        *do what you want here*
    }

    // checks if enter is clicked
    // if statement asks if in this frame, enter button is down
    // AND if enter button was not down in the last frame
    // this way, if statement below will fire only on each click
    if(newState.IsKeyDown(Keys.Enter) && oldState.IsKeyUp(Keys.Enter))
    {
        *do what you want here*
    }

    //set old state to new state, so the next frame knows 
    //what was happening in frame before that one
    oldState = newState;
}

答案 1 :(得分:1)

我怀疑键盘的状态只会在更新(...)周期之间刷新(或接近等效),因此循环不会做任何有用的事情。

要检测键盘状态的变化,您需要比较连续调用Update(...)之间的键盘状态

答案 2 :(得分:0)

重新启动计算机修复了问题,它一定是代码之外的错误。