How to use keyboard interactions with GLUT

Back to OpenGL Tutorial Index

This opengl tutorial will teach you how to add keyboard interaction to your opengl application through the use of glut and glut's keyboard calls. Now glut has many different keyboard calls, but in this opengl tutorial I will only be teaching you the very basics so that when you press the ESC key, glut will end your opengl application. You will have to look into my camera tutorials for more information on how to use the keyboard.

Using the keyboard is extrememly simple, you need a function for the keyboard
in this case 'keyboard', it must have '(unsigned char key, int x, int y)'
with code somewhat like what I have. Instead of 'if' you could easily change
that to 'switch' and then use 'case's. But anyway, all you have to edit after that
is the 'main' function. Just add the line:
glutKeyboardFunc (keyboard);
where 'keyboard' is the name of your keyboard function.

also keep in mind that because we are using GLUT we can easily gather input
from the arrow keys with GLUT_KEY_LEFT, UP, DOWN, RIGHT, along with the f1-12 keys.
to do that, just replace the 27 in this case to GLUT_KEY_DOWN.

#include <GL/gl.h>
#include <GL/glut.h>

void display (void) {
glClearColor (0.0,0.0,0.0,1.0);
glClear (GL_COLOR_BUFFER_BIT);
glLoadIdentity();
gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
glFlush();
}

void keyboard (unsigned char key, int x, int y) {
if (key==27) { //27 is the ascii code for the ESC key
exit (0); //end the program
}
}

int main (int argc, char **argv) {
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow ("A basic OpenGL Window");
glutDisplayFunc (display);
glutKeyboardFunc (keyboard);//the call for the keyboard function.
glutMainLoop ();
return 0;
}

Download C++ Source Code for this Tutorial

Download Visual Basic Source Code for this Tutorial

     

 

Copyright 2008, Donald Urquhart
Proudly supported by http://www.cdadc.com