I'm working on a project using GLUT. It is a simple demonstration of a car driving on a circle track. There are six inputs the user can give: g- start driving, e- end, h- helicopter view, s- side view, b- back view, f- front view. It was working well but I added a Timer function to slow down the car in place of the idle function but now pressing g does nothing to the car.
Timer function:
void Timer(int value) {
if(KEY == 'g'){
start=1;
}
if(start==1)
{
//KEY = keys;
angle+=0.05;
if(angle==TWO_PI)
{
angle-=TWO_PI;
}
carx=MID*sin(angle);
cary=MID*cos(angle);
switch(KEY)
{
case 'H':
case 'h':viewpoint=HELICOPTER;break;
case 'S':
case 's':viewpoint=SIDE;break;
case 'F':
case 'f':viewpoint=FRONT;break;
case 'B':
case 'b':viewpoint=BACK;break;
case 'E':
case 'e': start=0;break;
}
// next Timer call milliseconds later
glutPostRedisplay(); // Post re-paint request to activate display()
glutTimerFunc(100, Timer, start);
}
}
Keyboard callback function:
void keys(unsigned char key,int x,int y)
{
KEY=key;
if(key=='E' || key=='e')
{
start=0;
}
if(key=='G' || key=='g')
{
start=1;
}
}
This problem only started after replacing idle with timer. All other actions (h,f,b,s and e) are working. It's only the g. If I remove the if condition or set start to 1 in the beginning the cars runs as soon as the window opens but if stop it there's no restarting it by pressing g.
This is my first time working on GLUT and I can't figure out how to fix this problem. Please forgive me if the question is stupid or if the code is a mess.
I suspect that you start timer by invoking glutTimerFunc(100, Timer, start);
somewhere and since start
initially equals 0 if(start==1)
block is skipped and timer is not restarted.
Also you should remove all input handing code from Timer
. Handle input inside of dedicated callback and store delaed actions in some container to execute them later when timer callback is invoked.