Home » Intermediate » Lesson 7: OpenGL Keyboard Control

Lesson 7: OpenGL Keyboard Control

You will need to change the previous code for this tutorial.

OpenGL is used to communicate with the Graphical Processing Unit, so by default it does not contain keyboard control. You will need a library to communicate with the keyboard. We can use SDL (which we have been using all this time) to take keyboard input.
You may have noticed the function handleKeypress, we have extended it to:

/* function to handle key press events */
void handleKeyPress( SDL_keysym *keysym )
{
    switch ( keysym->sym )
        {
        case SDLK_ESCAPE:
            /* ESC key was pressed */
            Quit( 0 );
            break;
        case SDLK_F1:
            /* F1 key was pressed
             * this toggles fullscreen mode
             */
            SDL_WM_ToggleFullScreen( surface );
            break;

        case SDLK_RIGHT:
            ox ++;
            break;

        case SDLK_LEFT:
            ox--;
            break;
 
        case SDLK_UP:
            oz--;
            break;

        case SDLK_DOWN:
            oz++;
            break;

        default:
            break;
        }

    return;
}

Where ox,oy and oz are the objects position.
When drawing, we added the line:

    // draw cube
    glPushMatrix();
      glTranslatef(ox,oy,oz);
      drawCube();
    glPopMatrix();

Thus, using the cursor keys will move the object. :-)