Swiftless Game Programming Site
Home Tutorials Contact
Home
News
OpenGL
GLSL
OpenCL
Maths
Misc
Work in Progress
Resume
 
 

OpenGL tutorial on keyboard interaction using GLUT

If you would like to see this site updated, please help out and

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.

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
  #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


Comments:

Name: Daybe
Date: 2010-02-15 09:19:35
Comment:
Thanks for these tips, helped me when I tried to emplement keyboard interaction when I wanted to be able to switch between wireframe and filled mode.
Keep on the hard work !

XxX Daybe

Name: Baby Stuey
Date: 2010-02-28 19:08:19
Comment:
Don't forget the header for exit(), #include

Name: Baby Stuey
Date: 2010-02-28 19:09:33
Comment:
... stdlib.h
Name   Email


Reload Image

 
     

 

Copyright 2009, Donald Urquhart AKA Swiftless
Check out: http://www.cdadc.com