PDA

View Full Version : GLUT function for detecting when key is held down



dellatorre
01-08-2010, 06:06 PM
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, instead of having to repeatedly press/depress it.

ZbuffeR
01-09-2010, 03:15 AM
Glut does not work that way, it is event-driven.
So you receive a message when a key pushed down, and another when a key is released. Then it is possible to track the status 'by hand' in some kind of global array.
Or, if you are after more game-like behaviour, just use GLFW instead of GLUT, with glfwGetKey(myKey) you get the exact function you need.

dellatorre
01-09-2010, 02:52 PM
What I want to happen is that the movement continues when I hold down the up arrow key.

Here is snippets of my code:

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

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

display();
}

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;
}
display();

}

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


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

}


But its not working. When I hold down the up arrow key it doesn't continue to move, I still have to keep pressing the 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?

thanks :-))