import sys, time, math from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * from dmsgl import * camera = OrthoCamera(-10,10, -10,10, -10,10) light = Light() material = Material(diffuse=Color.Blue) ballXform = SimpleTransform() ballPos = Vector([0,0,0]) ballVel = Vector([10,4.5,0]) ballRadius = 1.0 def draw(): Color.Black.clear() camera.apply() light.apply() material.apply() ballXform.pushApply() gluSphere(quadric, ballRadius, 32, 16) ballXform.pop() material.disable() glutSwapBuffers() active = False def keyboard(key, x, y): global viewDistance, active if key == chr(27): sys.exit(0) elif key == ' ': active = not active prevTime = time.time() def checkForBounce(): if (ballPos[0]+ballRadius*0.7) > 10.0 and ballVel[0] > 0: ballVel[0] = -ballVel[0] elif (ballPos[0]-ballRadius*0.7) < -10.0 and ballVel[0] < 0: ballVel[0] = -ballVel[0] if (ballPos[1]+ballRadius*0.7) > 10.0 and ballVel[1] > 0: ballVel[1] = -ballVel[1] elif (ballPos[1]-ballRadius*0.7) < -10.0 and ballVel[1] < 0: ballVel[1] = -ballVel[1] def computeSquash(): x, y = 1, 1 if ballPos[0]+ballRadius > 10: x = (10.0 - ballPos[0]) / ballRadius if x <= 0.001: x = 0.001 y = 1.0 / x elif ballPos[0]-ballRadius < -10: x = (10.0 + ballPos[0]) / ballRadius if x <= 0.001: x = 0.001 y = 1.0 / x if ballPos[1]+ballRadius > 10: y = (10.0 - ballPos[1]) / ballRadius if y <= 0.001: y = 0.001 if x == 1: x = 1.0 / y elif ballPos[1]-ballRadius < -10: y = (10.0 + ballPos[1]) / ballRadius if y <= 0.001: y = 0.001 if x == 1: x = 1.0 / y return [x, y, 1] def update(): global prevTime, ballPos, ballVel, ballXform t = time.time() dt = t - prevTime prevTime = t if active: ballPos += ballVel * dt checkForBounce() ballXform.translate = ballPos ballXform.scale = computeSquash() glutPostRedisplay() glutInit([]) glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH) glutInitWindowSize(400,400) glutCreateWindow(sys.argv[0]) glutDisplayFunc(draw) glutKeyboardFunc(keyboard) glutIdleFunc(update) glEnable(GL_DEPTH_TEST) quadric = gluNewQuadric() glutMainLoop()