# This program draws a moving "car" with rotating wheel.s # It demonstrates the use of the glPushMatrix and glPopMatrix to # create a hierarchy of transformations. import sys import time from OpenGL.GLUT import * from OpenGL.GL import * from OpenGL.GLU import * angle = 0 carPosition = [-0.5, 0, 0] carDirection = 1 prevTime = time.time() def drawWheel(): glBegin(GL_QUADS) glVertex2f(-0.08, -0.08) glVertex2f(0.08, -0.08) glVertex2f(0.08, 0.08) glVertex2f(-0.08, 0.08) glEnd() def drawCar(): glPushMatrix() glTranslatef(carPosition[0], carPosition[1], carPosition[2]) glBegin(GL_QUADS) glVertex2f(-0.3, 0.0) glVertex2f(0.3, 0.0) glVertex2f(0.3, 0.2) glVertex2f(-0.3, 0.2) glEnd() glColor3f(1, 1, 0) # glPushMatrix() glTranslatef(-0.2, 0.0, 0.0) glRotatef(angle, 0, 0, 1) drawWheel() # glPopMatrix() glColor3f(1, 0, 0) glPushMatrix() glTranslatef(0.2, 0.0, 0.0) glRotatef(angle, 0, 0, 1) drawWheel() glPopMatrix() glPopMatrix() def draw(): global angle glLoadIdentity() glClear(GL_COLOR_BUFFER_BIT) glColor3f(0, 0, 1) drawCar() glutSwapBuffers() def keyboard(key, x, y): if key == chr(27): sys.exit(0) def update(): global angle, carPosition, carDirection global prevTime currentTime = time.time() deltaTime = currentTime - prevTime prevTime = currentTime angle = angle - 180 * deltaTime * carDirection carPosition[0] = carPosition[0] + deltaTime * carDirection if carPosition[0] * carDirection > 1: carDirection = -carDirection glutPostRedisplay() glutInit([]) glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB) glutInitWindowSize(300, 300) glutInitWindowPosition(0,0) glutCreateWindow(sys.argv[0]) glutDisplayFunc(draw) glutKeyboardFunc(keyboard) glutIdleFunc(update) glutMainLoop()