Check Q button is held down using GLUT?

1.7k views Asked by At

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?

2

There are 2 answers

0
aslg 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
}
2
Rugruth On

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:

bool is_q_pressed = false;

void KeyboardHandler(unsigned char key, int x, int y) 
{
    switch (key)
    {
    case "q":
    case "Q":
        is_q_pressed = !is_q_pressed;
        if (is_q_pressed)
          // do something... or elsewhere in program
        break;
    }
}

void KeyboardUpHandler(unsigned char key, int x, int y) 
{
    switch (key)
    {
    case "q":
    case "Q":
        is_q_pressed = false;
        break;
    }
}


int main()
{
    // Other glut init functions...
    ...
    // Keyboard handler
    glutKeyboardFunc(KeyboardHandler);
    // Keyboard up handler
    glutKeyboardUpFunc(KeyboardUpHandler);
    ...
    glutMainLoop();

    return 0;
}

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 :)