利用opengl实现了反弹小方块的效果,蓝宝书代码并不全,所以自己实现了没有缺少的部分。
#include "../../shared/gltools.h"
GLfloat x1 = 0.0f;
GLfloat y1 = 0.0f;
GLfloat rSize = 50.0f;
GLfloat xStep = 5.0f;
GLfloat yStep = 5.0f;
GLfloat windowWidth = 400;
GLfloat windowHeight = 300;
void RenderScene(void){
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0f,0.0f,0.0f);
glRectf(x1,y1,x1+rSize,y1-rSize);
glutSwapBuffers();
}
void Change(GLsizei w,GLsizei h){
GLfloat aspectRatio;
if(h==0)
h=1;
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
aspectRatio = (GLfloat)w/(GLfloat)h;
if(w<=h){
glOrtho(-h/2,h/2,-w/2*aspectRatio,w/2*aspectRatio,1.0,-1.0);
windowWidth = w/2*aspectRatio;
windowHeight = h/2;
}
else{
glOrtho(-h/2*aspectRatio,h/2*aspectRatio,-w/2,w/2,1.0,-1.0);
windowWidth = h/2*aspectRatio;
windowHeight = w/2;
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void SetClearColor(void){
glClearColor(0.0f,0.0f,1.0f,1.0f);
}
void TimerFunction(int value){
if(x1>windowWidth - rSize || x1< -windowWidth)
xStep = -xStep;
if(y1>windowHeight || y1<-windowHeight+rSize)
yStep = -yStep;
x1+=xStep;
y1+=yStep;
if(x1>(windowWidth-rSize+xStep))
x1=windowWidth - rSize -1;
else if(x1<-(windowWidth+xStep))
x1=-windowWidth -1;
if(y1>(windowHeight+yStep))
y1=windowHeight - 1;
else if(y1<-(windowHeight-rSize+yStep))
y1=-windowHeight+rSize-1;
glutPostRedisplay();
glutTimerFunc(33,TimerFunction,1);
}
int main(int argc,char* argv[]){
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(800,600);
glutCreateWindow("lqwang");
glutDisplayFunc(RenderScene);
glutReshapeFunc(Change);
glutTimerFunc(33,TimerFunction,1);
SetClearColor();
glutMainLoop();
return 0;
}