-
简介
用OpenGL画一个正方形。让这个正方形在窗口的边框反弹,使得正方形在窗口四处移动。
回调函数glutTimerFunc(间隔秒数, 调用函数func,传送一个用户定义值value)
被定时器调用的函数原型为TimerFunction(value),和windows定时器不一样,这个函数只激发一次。为了实现连续的动画,必须在定时器函数中再次重新设置定时器。
在GLRect 程序中,可以把矩形位置的硬编码值改为变量(全局变量),然后在定时器函数中不断修改这些变量,这样就使得矩形像是在窗口移动。当矩形移动时,我们需要跟踪矩形的位置和大小,并考虑到窗口大小的改变。
-
代码
#coding:utf-8
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
x1 = 100.0
y1 = 150.0
rsize = 50
#方向
xstep = 2.0
ystep = 2.0
def RenderScene():
global x1,y1,rsize
#清除之前画面
glClear(GL_COLOR_BUFFER_BIT)
glColor3f(1.0,0.0, 0.0) #不透明,填充颜色红色
glRectf(x1, y1, x1+rsize, y1+rsize) #画矩形
#交换缓冲区显示
glutSwapBuffers();
#设置渲染状态
def SetupRC():
glClearColor(0.0, 0.0, 1.0, 1.0) #背景蓝色
#改变窗口大小时调用
def ChangeSize(w,h):
global windowWidth,windowHeight
if(h == 0): #防止除数为0
h = 1
glViewport(0, 0, w, h)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
if (w <= h):
windowHeight = 250.0*h/w
windowWidth = 250.0
else:
windowWidth = 250.0*w/h
windowHeight = 250.0
# 设置修剪窗口
glOrtho(0.0, windowWidth, 0.0, windowHeight, 1.0, -1.0)
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
def TimerFunction(value):
global x1,y1,rsize,xstep,ystep
# 当到达左、右边界时反转方向
if (x1 > windowWidth-rsize or x1 < 0):
xstep = -xstep
# 到达上、下边界时反转方向
if (y1 > windowHeight-rsize or y1 < 0):
ystep = -ystep
# 检查界限. This is incase the window is made
# smaller and the rectangle is outside the new clipping volume
if (x1 > windowWidth-rsize):
x1 = windowWidth-rsize-1
if (y1 > windowHeight-rsize):
y1 = windowHeight-rsize-1
# 移动方块
x1 += xstep;
y1 += ystep;
# 新条件下重画
glutPostRedisplay()
glutTimerFunc(33,TimerFunction, 1)
#使用glut初始化OpenGL
glutInit()
#显示模式:GLUT_SINGLE无缓冲直接显示|GLUT_RGB采用RGB
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB)
glutCreateWindow(b"Bounce")
#调用函数绘制图像
glutDisplayFunc(RenderScene)
glutReshapeFunc(ChangeSize)
glutTimerFunc(33, TimerFunction, 1)
SetupRC()
#主循环
glutMainLoop()