Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify a keyboard's directional keys in glut?

Tags:

opengl

glut

I wanna use up, down, left, right as part of the controls of an opengl + glut application. How do I refer to the keys inside my 'keyboard' function (the one that I pass to glutKeyboardFunc)?

like image 863
andandandand Avatar asked Nov 22 '10 18:11

andandandand


People also ask

What is glutKeyboardFunc?

Description. glutKeyboardFunc sets the keyboard callback for the current window. When a user types into the window, each key press generating an ASCII character will generate a keyboard callback. The key callback parameter is the generated ASCII character.


2 Answers

You need glutSpecialFunc.

For example -

#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();
}
like image 95
tibur Avatar answered Oct 16 '22 18:10

tibur


your functions should be something like these

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;
 }
}

and you also need to invoke these in your main() method

 glutSpecialFunc(handleSpecialKeypress);
 glutSpecialUpFunc(handleSpecialKeyReleased);
  • The variables isRightKeyPressed and isLeftKeyPressed are global variables I defined.
like image 28
hectorg87 Avatar answered Oct 16 '22 19:10

hectorg87