What function can I use to check if the Q button (or any other button is pressed down) and what will be the value needed to specify this for the Q button?
Check Q button is held down using GLUT?
1.7k Views Asked by Barney Chambers At
2
There are 2 best solutions below
0
On
The simplest thing you can do is to use an array of bools with enough bools to contain the 256 regular keys and the special keys (right, left, etc.. ).
bool keys[256];
Use the KeyDown func to set the matching key to true, and KeyUp to set false.
void KeyboardDown( int key, int x, int y ) {
if ( isalpha( key ) ) {
key = toupper( key );
}
keys[ key ] = true;
}
void KeyboardUp( int key, int x, int y ) {
if ( isalpha( key ) ) {
key = toupper( key );
}
keys[ key ] = false;
}
The toupper just makes sure that pressing q or Q is the same whether Caps-lock is on or off. You don't have to use it if you don't need it.
Then somewhere in the update code you can check if a key was pressed like
if ( keys['Q'] ) {
// do things
}
Using glut you need to define a Keyboard Handler function, and tell GLUT to use it for handling key strokes. Something along the lines of:
EDIT: Added support for keyboard up. Using global variables isn't the best practice, but GLUT almost forces you to use them to keep track of program states. The good thing is that you can use the global variable (is_q_pressed) anywhere in your program... like in the idle() for some logic, or in the draw function to draw something if that key is pressed.
And, as @aslg said, you can make an array of bools to keep track of every key pressed, check his answer for ideas too :)