Glut Keyboard
2002-04-02 02:11:13
Category: cpp:opengl
Description: Interact with the keyboard using the glut library.
Author: detour
Viewed: 4704
Rating: (18 votes)


/* glutkey.cpp written by detour@metalshell.com
 *
 * Shows how to use the keyboard function with glut.
 *
 * In order to get this to compile you must have the opengl
 * libraries, and header files.  Be sure to include opengl32.lib
 * glut32.lib and glu32.lib when compiling. 
 *
 * http://www.metalshell.com/
 *
 */
 
#include <windows.h>
#include <math.h>
#include <gl/Gl.h>
#include <gl/Glu.h>
#include <gl/glut.h>
 
class Point {
public:
    double x,y;
    Point() { x = 0.0; y = 0.0; }
};
 
Point P;
 
void myInit() {
    glClearColor(0.0,0.0,0.0,0.0);
    glViewport(0,0,800,600);
    glColor3f(0.2f,0.8f,0.6f);
}
 
void drawDot() {
    glClear(GL_COLOR_BUFFER_BIT);
    glBegin(GL_POINTS);
        glVertex2f(P.x, P.y);
    glEnd();
    glutSwapBuffers();
}
 
void myDisplay() {
    drawDot();
}
 
void myKeyboard(unsigned char theKey, int mouseX, int mouseY) {
    switch (theKey)
    {
        case 'e':
            P.y += .005;
            drawDot();
            break;
        case 'd':
            P.y -= .005;
            drawDot();
            break;
        case 's':
            P.x -= .005;
            drawDot();
            break;
        case 'f':
            P.x += .005;
            drawDot();
            break;
        default:
            break;
    }
}
 
int main(int argc, char *argv[]) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
    glutInitWindowSize(800,600);
    glutInitWindowPosition(0,0);
    glutCreateWindow("Keyboard Function");
 
    glutDisplayFunc(myDisplay);
    glutKeyboardFunc(myKeyboard);
 
    myInit();
    glutMainLoop();
 
    return 0;
}