Omegastick
Omegastick

Reputation: 1901

Xna's KeyboardState.IsKeyDown() gets stuck once key is pressed

When running the following code in a loop (var enterKey = Keyboard.GetState().IsKeyDown(Keys.Enter);) pushing the enter key returns true even after I've released the key.

Any ideas as to what I'm doing wrong?

Upvotes: 1

Views: 649

Answers (3)

Omegastick
Omegastick

Reputation: 1901

Restarting my computer fixed the problem, it must have been a bug outside of the code.

Upvotes: 0

Monset
Monset

Reputation: 657

Try checking like this:

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

This way, on each update you are updating current keyboard state (which keys are pressed), so you can check for different key presses in each frame.

EDIT:
You are likely to want to check for a single click, so instead of asking 2 question, here is a "bonus" to your question. Code is similar:

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;
}

Upvotes: 3

lzcd
lzcd

Reputation: 1353

I suspect the state of the keyboard only gets refreshed between Update(...) cycles (or a close equivalent thereof) so looping is not going to do anything useful.

To detect changes in keyboard state, you'll want to compare keyboard states between successive calls to Update(...).

Upvotes: 1

Related Questions