Question

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!

Was it helpful?

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

OTHER TIPS

Here's a link I found to a blog that talks about how to get the time in glut to display frames per second.

http://www.lighthouse3d.com/tutorials/glut-tutorial/frames-per-second/

You need to decide what the velocity of your ball is in pixels/second. Then multiply that velocity by the number of seconds that have elapsed between your last update & the current update. According to the blog, you can get this via glutGet(GLUT_ELAPSED_TIME). If that doesn't work, google for how to find the current time in milliseconds on your platform.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top