如何在过剩中指定键盘的方向键?

时间:2010-11-22 18:58:40

标签: opengl glut

我想用up,down,left,right作为opengl + glut应用程序控件的一部分。如何引用我的“keyboard”函数中的键(我传递给glutKeyboardFunc的键)?

2 个答案:

答案 0 :(得分:4)

您需要glutSpecialFunc

例如 -

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

void
init(void)
{
    /*initialize the x-y co-ordinate*/
    glClearColor(0,0,0,0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(-320, 319,-240, 239);
    glClear (GL_COLOR_BUFFER_BIT);

    glFlush();
}

void
catchKey(int key, int x, int y)
{
    if(key == GLUT_KEY_LEFT)    
        printf("Left key is pressed\n");
    else if(key == GLUT_KEY_RIGHT)
        printf("Right key is pressed\n");
    else if(key == GLUT_KEY_DOWN)
        printf("Down key is pressed\n");
    else if(key == GLUT_KEY_UP)
        printf("Up key is pressed\n");
}

int
main(int argc, char *argv[])
{
    double x_0, y_0, x_1, y_1;
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(640, 480);
    glutInitWindowPosition(400, 400);

    glutCreateWindow("Special key");
    init();
    glutSpecialFunc(catchKey);
    glutMainLoop();
}

答案 1 :(得分:4)

你的功能应该是这样的

void handleSpecialKeypress(int key, int x, int y) {
 switch (key) {
 case GLUT_KEY_LEFT:
  isLeftKeyPressed = true;
  if (!isRightKeyPressed) {
        DO SOMETHING HERE;
  }
  break;
 case GLUT_KEY_RIGHT:
  isRightKeyPressed = true;
  if (!isLeftKeyPressed) {
        DO SOMETHING HERE;
  }
  break;
 }
}

void handleSpecialKeyReleased(int key, int x, int y) {
 switch (key) {
 case GLUT_KEY_LEFT:
  isLeftKeyPressed = false;
  break;
 case GLUT_KEY_RIGHT:
  isRightKeyPressed = false;
  break;
 }
}

你还需要在main()方法中调用它们

 glutSpecialFunc(handleSpecialKeypress);
 glutSpecialUpFunc(handleSpecialKeyReleased);
  • 变量 isRightKeyPressed isLeftKeyPressed 是我定义的全局变量。