korimusk
korimusk

Reputation: 51

Stopping animation with a key using GLUT?

I design an UFO that speeds in coordinate x. However, I would like to stop animation -I mean increasing the x coordinate when I press to spacebar.

I defined x and y coordinates as global variable.

int xB = 0, yB = 0;

And, here is the increment function.

#if TIMER_ON == 1
void onTimer(int v) {

    glutTimerFunc(TIMER_PERIOD / 30, onTimer, 0);
    if (xB < (WINDOW_WIDTH / 2) - 80)
        xB++;
    if (xK < (WINDOW_WIDTH / 2) - 100)
        xK += 2;
    glutPostRedisplay(); // display()

}
#endif

I don't know which GLUT function that I'm going to use to stop the animation.

Upvotes: 1

Views: 623

Answers (1)

genpfault
genpfault

Reputation: 52083

Create a glutKeyboardFunc() callback that toggles an isAnimating bool. Then check isAnimating in onTimer().

For example:

bool isAnimating = true;
void keyboard( unsigned char key, int x, int y )
{
    if( ' ' == key )
    {
        isAnimating = !isAnimating;
    }
}

void onTimer(int v)
{
    glutTimerFunc(TIMER_PERIOD / 30, onTimer, 0);
    if( isAnimating )
    {
        if (xB < (WINDOW_WIDTH / 2) - 80)
            xB++;
        if (xK < (WINDOW_WIDTH / 2) - 100)
            xK += 2;
        glutPostRedisplay(); // display()
    }
}

Don't forget to register the callback via glutKeyboardFunc(keyboard) sometime before you call glutMainLoop().

Upvotes: 1

Related Questions