// Keyboard demo. Shows how to use more than one key on the keyboard // at a time. Demo has a red box on a black background and user can // use arrow keys or the 'w', 'a', 's', 'd' keys to move the box // around the screen, the point being that you can hold more than // one key down at a time and the box will move accordingly (ie. // diagonally). //#include #include #include // Initial square position and size float xPos = 320.0; float yPos = 240.0; GLsizei rsize = 25; #define FALSE 0 #define TRUE 1 int up = FALSE; int down = FALSE; int left = FALSE; int right = FALSE; void moveObject(void) { if(left) { xPos -= 4.0; // Keep it inside of the box if(xPos-rsize < 0.0) xPos = 0.0+rsize; } if(right) { xPos += 4.0; // Keep it inside of the box if(xPos+rsize > 640.0) xPos = 640.0-rsize; } if(up) { yPos += 4.0; // Keep it inside of the box if(yPos+rsize > 480.0) yPos = 480.0-rsize; } if(down) { yPos -= 4.0; // Keep it inside of the box if(yPos-rsize < 0.0) yPos = 0.0+rsize; } } void myDisplay(void) { glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0f, 0.0f, 0.0f); moveObject(); glRectf(xPos-rsize, yPos-rsize, xPos+rsize, yPos+rsize); glutSwapBuffers(); } void TimerFunc(int value) { myDisplay(); glutPostRedisplay(); glutTimerFunc(33,TimerFunc, 1); } void myInit(void) { glClearColor(0.0, 0.0, 0.0, 0.0); glColor3f(0.0f, 0.0f, 0.0f); glPointSize(1.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, 640.0, 0.0, 480.0); } void pressKey(unsigned char key, int x, int y) { switch (key) { case 'a': left = TRUE; break; case 'd': right = TRUE; break; case 'w': up = TRUE; break; case 's': down = TRUE; break; } } void releaseKey(unsigned char key, int x, int y) { switch (key) { case 'a': left = FALSE; break; case 'd': right = FALSE; break; case 'w': up = FALSE; break; case 's': down = FALSE; break; } } void pressKeySpecial(int key, int x, int y) { switch (key) { case GLUT_KEY_LEFT : left = TRUE; break; case GLUT_KEY_RIGHT : right = TRUE; break; case GLUT_KEY_UP : up = TRUE; break; case GLUT_KEY_DOWN : down = TRUE; break; } } void releaseKeySpecial(int key, int x, int y) { switch (key) { case GLUT_KEY_LEFT : left = FALSE; break; case GLUT_KEY_RIGHT : right = FALSE; break; case GLUT_KEY_UP : up = FALSE; break; case GLUT_KEY_DOWN : down = FALSE; break; } } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(640, 480); glutInitWindowPosition(50, 50); glutCreateWindow("KeyBoard Test"); glutDisplayFunc(myDisplay); glutTimerFunc(33, TimerFunc, 1); glutSpecialFunc(pressKeySpecial); glutSpecialUpFunc(releaseKeySpecial); glutKeyboardFunc(pressKey); glutKeyboardUpFunc(releaseKey); myInit(); glutMainLoop(); return 1; }