Chris
Chris

Reputation: 3688

How to make action on keyboard input be instant

I am writing in C++ and using OpenGL in Windows.
I've created a cube and I want it to be rotated around the y axis ( using glRotate3f(), not gluLookat() ) by pressing '4' or '6' numpad keys.
The problem is that when I press any key, there is a slight rotation and then stops for a while and then it starts rotating continuously.

Is there any way to achieve this by using glutkeyboardfunc?

If not, how can it be achieved?

Upvotes: 1

Views: 3077

Answers (1)

genpfault
genpfault

Reputation: 52082

Maintain your own key state map and trigger redraws on a timer:

// g++ main.cpp -o main -lglut -lGL -lGLU && ./main
#include <GL/glut.h>
#include <map>

bool paused = false;
std::map< unsigned char, bool > state;
void keyboard_down( unsigned char key, int x, int y )
{
    if( key == 'p' )
        paused = !paused;

    state[ key ] = true;
}

void keyboard_up( unsigned char key, int x, int y )
{
    state[ key ] = false;
}

void display()
{
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    double w = glutGet( GLUT_WINDOW_WIDTH );
    double h = glutGet( GLUT_WINDOW_HEIGHT );
    double ar = w / h;
    glOrtho( -2 * ar, 2 * ar, -2, 2, -1, 1);

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    static float angle = 0;
    if( state[ '6' ] )  angle -= 3;
    if( state[ '4' ] )  angle += 3;
    if( !paused )
        angle += 0.5;

    glPushMatrix();
    glRotatef( angle, 0, 0, 1 );

    glColor3ub( 255, 0, 0 );
    glBegin( GL_QUADS );
    glVertex2i( -1, -1 );
    glVertex2i(  1, -1 );
    glVertex2i(  1,  1 );
    glVertex2i( -1,  1 );
    glEnd();

    glPopMatrix();

    glutSwapBuffers();
}

void timer( int extra )
{
    glutPostRedisplay();
    glutTimerFunc( 16, timer, 0 );
}

int main( int argc, char **argv )
{
    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE );
    glutInitWindowSize( 640, 480 );
    glutCreateWindow( "Keyboard" );
    glutDisplayFunc( display );
    glutKeyboardFunc( keyboard_down );
    glutKeyboardUpFunc( keyboard_up );
    glutTimerFunc( 0, timer, 0 );
    glutIgnoreKeyRepeat( GL_TRUE );
    glutMainLoop();
    return 0;
}

Upvotes: 1

Related Questions