I'm using openGl's glutTimerFunc to reDraw all the element every 5 ms and there are also a couple of event handlers for mouse and keyboard keys that I'm using. The problem is the every time a mouse click happens for some reason display function is called and that causes the animation becomes faster and faster with each click.
These are the methods that are causing the problem and how I wrote the code.
Main
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInitWindowSize((int)WINDOW_WIDTH, (int)WINDOW_HEIGHT);
glutInitWindowPosition(150, 10);
glutCreateWindow("OpenGl");
glutDisplayFunc(display);
glutSpecialFunc(arrowKeyFunc);
glutSpecialUpFunc(arrowKeyUp);
glutReshapeFunc(reshape);
glutTimerFunc(10, ballMotionHandler, 0);
glutMouseFunc(mouseFunc);
glColor3f(1.0, 0, 0);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutMainLoop();
}
Display
void display(void)
{
printf("tick\n");
glClearColor(.3980f, .4001f, 0.7f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glPointSize(3);
drawRect(-1.0, 1.0f - TOP_BAR_HEIGHT, WINDOW_WIDTH, TOP_BAR_HEIGHT, getColor(.0, .0, .0));
drawCircle(center.x + cw, center.y + ch, r, 800, getColor(1.3, .5, .00));
drawRect(racket.x, racket.y, .49, .09, getColor(.760, .31, .19));
ballMotionHandler();
racketMotionHandler();
glFlush();
glutSwapBuffers();
glutTimerFunc(5, mydisplay, 0);
}
MouseFunc
void mouseFunc(int button, int state, int x, int y)
{
mouse.x = x;
mouse.y = y;
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN&¢er.x == 0.0f)
{
float tmp = sqrtf(powf(((x - WINDOW_WIDTH / 2) / (WINDOW_WIDTH / 2) - center.x), 2) + powf(((y - WINDOW_HEIGHT / 2) / (WINDOW_HEIGHT / 2) - center.y), 2));
cw = ((x - WINDOW_WIDTH / 2) / (WINDOW_WIDTH / 2) - center.x) / (ratio*tmp);
ch = -((y - WINDOW_HEIGHT / 2) / (WINDOW_HEIGHT / 2) - center.y) / (ratio*tmp);
cw *= pow(1.125, level);
ch *= pow(1.125, level);
printf("\nspeed of ball when <level = %d> equal %f", level, sqrtf(powf(cw, 2) + powf(ch, 2)));
}
}
Every time I click left mouse button 'tick' is printed one more time every 5 ms (I tested with 1000 ms so I know it does). At first it's one 'tick' every 5ms after first click it's 2 time, second click 3 times and so on.
what is causing this? Is there a better solution than using glutTimerFunc ( or glutIdleFunc!)?