Skip to main content
GameDev.net gamedev.net
🔒 Locked

GLUT function for detecting when key is held down

Started by dellatorre Jan 8, 2010 at 6:28 PM 3 replies 14.4k views
Original Post
dellatorre
dellatorre
Is there a GLUT function for detecting when a key is held down? like when you hold down the up arrow key to go forward.
fcoelho
fcoelho
A key that is held down is just a key that was pressed and not released yet. Register a function with glutKeyboardFunc to find if a key was pressed and glutKeyboardUpFunc to find out when it is released.
dellatorre
dellatorre
ok.

Here are some snippets of my code:

glutSpecialFunc(specialChar);
glutSpecialUpFunc(keyBoardUp);


and here are those 2 functions:

void specialChar( int key, int x, int y )
{
switch( key ) {
case GLUT_KEY_UP:
speed += 0.06f;
upKeyPressed = true;
break;
case GLUT_KEY_DOWN:
if ( speed > 0.01f )
speed -= 0.01f;
else
speed = 0;
break;
case GLUT_KEY_RIGHT:
rotate( 3, 0, 1, 0 );
break;
case GLUT_KEY_LEFT:
rotate( -3, 0, 1, 0 );
break;
}
}

void keyBoardUp( int key, int x, int y )
{
switch( key ) {
case GLUT_KEY_UP:
speed = 0;
upKeyPressed = false;
break;
case GLUT_KEY_DOWN:
speed = 0;
break;
case GLUT_KEY_RIGHT:
speed = 0;
break;
case GLUT_KEY_LEFT:
speed = 0;
break;
}
}


As you can see above, I added in the boolean upKeyPressed, per your suggestion.
Now I want to put a statement like "if (upKeyPressed) speed += 0.06f;" so that the movement will continue as long as the up arrow key is held down, but I'm not sure where in my program I should put this statement.

Do you have any suggestions?

thanks :-)

Deliverance
Deliverance
Just put it in the idle function:

void myIdleFunc(){   if (upKeyPressed) speed += 0.06f;}glutIdleFunc(myIdleFunc);
dellatorre
dellatorre
I added in the idle function:

glutIdleFunc(update);
.
.
void update()
{
if (upKeyPressed) {
speed += 0.06f;
translate(0,0,speed);
display();
}
}


void translate( GLfloat x, GLfloat y, GLfloat z )
{
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef( x, y, z );
glMultMatrixf( modelViewMatrix );
glGetFloatv( GL_MODELVIEW_MATRIX, modelViewMatrix );

}

void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glColorMaterial( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE );
redsquare();
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf( modelViewMatrix );
worldCube();
glFlush();
glutSwapBuffers();
}


but when I hold down the up arrow key it doesn't continue to move, I still have to keep pressing it. What I want to happen is the movement continue when I hold down the up arrow key.
I tried replacing the "if" statement in my "update" function with a "while" statement, but that just gives me an infinite loop, and the movement doesn't stop when I release the up arrow key.

Any suggestions?


Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.