Search code examples
c++opengltimerpong

C++ OpenGL Pong ball moving too fast


Im trying to create a simple pong game in C++ using opengl. I have the borders displaying on the screen, the paddles, the ball, and all of them move, so that's great! The problem is that the ball moves lightning fast even at one pixel of speed.

Im updating it's position in a call-back function called init which I then pass into glutIdleFunc like so: glutIdleFunc(idle);

the idle function is as follows:

void idle(){
    ball.moveLeft();

    glutPostRedisplay();
}

essentially im just having it move left by one pixel but, I guess that idle gets called a lot so it moves lightning fast. How do I fix this error?

If there's more information you need just ask!


Solution

  • Use a GLUT timer to kick your display() callback every 16 milliseconds:

    void timer( int extra )
    {
        glutPostRedisplay();
        glutTimerFunc( 16, timer, 0 );
    }
    
    int main( int argc, char **argv )
    {
        glutInit( &argc, argv );
        glutInitDisplayMode( ... );
        glutInitWindowSize( ... );
        glutCreateWindow( ... );
        ...
        glutTimerFunc( 0, timer, 0 );
        ...
        glutMainLoop();
        return 0;
    }