How to handle keyboard input correctly?

Started by BionicWave, January 03, 2013, 20:40:20

Previous topic - Next topic

BionicWave

Hi,
i have a little problem with how to handle rapid keyboard events.
I have an opengl-project in which i want to switch from game to a menu with KEY_ESCAPE.
Once in the menu i want to be able to switch back to the game with the same key: KEY_ESCAPE.
Problem is that pressing the escape-key generates about 120 keyevents.
I tried to loop through the key events in different ways, but either the program hangs or the
eventcount is the same after leaving the loop.
Is there a way to clear the keyboard-buffer?

thanks in advance
BionicWave

Daslee

I think that you're checking with if(Keyboard.isKeyDown(key)). If so, then try this:

while(Keyboard.next()){
	if(Keyboard.getEventKeyState()){
		switch(Keyboad.getEventKey()){
		case Keyboard.KEY_ESCAPE:
			//do something
			break;
		}
	}
}

BionicWave

Woohoo. That works fine.
Here´s my code:

while(Keyboard.next()){
  if(Keyboard.getEventKeyState()){
    switch (Keyboard.getEventKey()){
      case (Keyboard.KEY_ESCAPE):
        if (state == State.GAME){
          state = State.MAIN_MENU;
        } else {
          state = State.GAME;
        }
        break;
        
        case (Keyboard.KEY_RETURN):
          if (state == State.INTRO){
            state = State.GAME;
          } else
          if (state == State.MAIN_MENU)
          {
            state = State.EXIT;
          }
          break;
      }
    }
  }


Thanks a lot, Daslee.