Question

I'm trying to rotate a red triangle and a green triangle one after another after a constant time interval. I tried the following code and the time interval is not constant.I can't figure out the problem.

 static void display(void)
{
    now=glutGet(GLUT_ELAPSED_TIME);
    elapsedTime = now - interval;

    if(flag)
    {
        if(now%3000==0)
        {
            flag=false;

        }

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glColor3f(1,0,0);
        glRotatef(0.1,0.0,0.0,1.0);
        glBegin(GL_TRIANGLES);
        glVertex3f(-0.5f, 0.5f, -5.0f);
        glVertex3f(-1.0f, 1.5f, -5.0f);
        glVertex3f(-1.5f, 0.5f, -5.0f);
        glEnd();
        glutSwapBuffers();

    }
    else
    {
        if(now%3000==0)
        {
            flag=true;
        }

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glColor3f(0,1,0);
        glRotatef(-0.1,0.0,0.0,1.0);
        glBegin(GL_TRIANGLES);
        glVertex3f(-0.5f, 0.5f, -5.0f);
        glVertex3f(-1.0f, 1.5f, -5.0f);
        glVertex3f(-1.5f, 0.5f, -5.0f);
        glEnd();
        glutSwapBuffers();

    }

}
Was it helpful?

Solution

Before anything, have you tried debug 101: print key variables? I am pretty confident that if do cout << now % 3000 << endl you can find the source of the problem yourself.

For the answer:

now % 3000 == 0

Does not seem like a good idea.

How can you be sure that glutGet(GLUT_ELAPSED_TIME) will increment as 1, 2, 3, ...? What if rendering one frame takes 2 ms and the following happens: 2998, 2999, 3001? You just lost one switch time.

Due to the unpredictable time taken to redraw, it is difficult to be perfectly precise on about rendering times.

In your case, a good approximation could be:

now % 6000 < 3000

This should work well because 3s is much larger than the frequency at which the display will be called.

In most applications however, we want continuous movement, and the best option is to make movement proportional to the actual time lapses with code like:

float dt;
int t, oldT;

t = glutGet(GLUT_ELAPSED_TIME);
dt = (t - oldT)/1000.0;
oldT = t;
drawTriangle(rotationSpeed * dt);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top