LWJGL Forum

Programming => Lightweight Java Gaming Library => Topic started by: BionicWave on January 03, 2013, 20:40:20

Title: How to handle keyboard input correctly?
Post by: BionicWave on January 03, 2013, 20:40:20
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
Title: Re: How to handle keyboard input correctly?
Post by: Daslee on January 03, 2013, 20:47:35
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;
}
}
}
Title: Re: How to handle keyboard input correctly?
Post by: BionicWave on January 03, 2013, 21:14:42
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.