I found some code online which will move a box across the screen, then reset it after the box hits the end of the screen.
Here is the code:
void display(void) {
int sign = 1;
if (lastFrameTime == 0) {
/*
* sets lastFrameTime to be the number of milliseconds since
* Init() was called;
*/
lastFrameTime = glutGet(GLUT_ELAPSED_TIME);
}
int now = glutGet(GLUT_ELAPSED_TIME);
int elapsedMilliseconds = now - lastFrameTime;
float elapsedTime = float(elapsedMilliseconds) / 1000.0f;
lastFrameTime = now;
int windowWidth = glutGet(GLUT_WINDOW_WIDTH);
if (boxX > windowWidth) {
boxX -= windowWidth;
}
boxX += (sign)*256.0f * elapsedTime;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
//creates a new matrix at the top that we can do things to?
glTranslatef(boxX, 0.0f, 0.0f);
/*
* draw a "quad" (rectangle)
*/
glBegin(GL_QUADS);
glVertex2f(0.0f, 0.0f);
glVertex2f(128.0f, 0.0f);
glVertex2f(128.0f, 128.0f);
glVertex2f(0.0f, 128.0f);
glEnd();
glPopMatrix();
//pops that matrix off the stack so we can have a "clean" version to do something next time.?
glutSwapBuffers();
}
Now, the way I understand glPushMatrix()
and glPopMatrix()
is that glPushMatrix()
puts (or pushes) a new matrix on the stack for you to do things to, so that after you pop it back off you have a "clean" slate again. This is why, if I neglect the glPopMatrix()
after glEnd()
, my square seems to accelerate rather than move at a constant velocity.
How is it, however, that the changes I make inside of glPushMatrix()
and glPopMatrix()
are kept? When I use glPushMatrix()
and make a change to the top matrix, it visualizes the changes, but when i use glPopMatrix()
, aren't all those changes gone? When I am restored to a "clean" slate again, how is it that my box moves across the screen?
How is the state of that translation recorded if i just pop the matrix off again after making the change?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…