头文件不变
LUtil.h
GLfloat gCameraX = 0.f, gCameraY = 0.f;//相机位置
bool initGL()
{
glViewport( 0.f, 0.f, SCREEN_WIDTH, SCREEN_HEIGHT );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();//加载投影矩阵为单位矩阵
glOrtho( 0.0, SCREEN_WIDTH, SCREEN_HEIGHT, 0.0, 1.0, -1.0 );//缩放到全屏
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();//加载模型矩阵为单位矩阵
glPushMatrix();//保存模型矩阵到栈里面
glClearColor( 0.f, 0.f, 0.f, 1.f );
GLenum error = glGetError();
if( error != GL_NO_ERROR )
{
printf( "Error initializing OpenGL! %s\n", gluErrorString( error ) );
return false;
}
return true;
}
void render()
{
glClear( GL_COLOR_BUFFER_BIT );
glMatrixMode( GL_MODELVIEW );
glPopMatrix();//弹出栈里的矩阵到当前矩阵
glPushMatrix();//保存当前矩阵到栈里
glTranslatef( SCREEN_WIDTH / 2.f, SCREEN_HEIGHT / 2.f, 0.f );//移到屏幕中心
glBegin( GL_QUADS );
glColor3f( 1.f, 0.f, 0.f );
glVertex2f( -SCREEN_WIDTH / 4.f, -SCREEN_HEIGHT / 4.f );
glVertex2f( SCREEN_WIDTH / 4.f, -SCREEN_HEIGHT / 4.f );
glVertex2f( SCREEN_WIDTH / 4.f, SCREEN_HEIGHT / 4.f );
glVertex2f( -SCREEN_WIDTH / 4.f, SCREEN_HEIGHT / 4.f );
glEnd();
glTranslatef( SCREEN_WIDTH, 0.f, 0.f );//右边
glBegin( GL_QUADS );
glColor3f( 0.f, 1.f, 0.f );
glVertex2f( -SCREEN_WIDTH / 4.f, -SCREEN_HEIGHT / 4.f );
glVertex2f( SCREEN_WIDTH / 4.f, -SCREEN_HEIGHT / 4.f );
glVertex2f( SCREEN_WIDTH / 4.f, SCREEN_HEIGHT / 4.f );
glVertex2f( -SCREEN_WIDTH / 4.f, SCREEN_HEIGHT / 4.f );
glEnd();
glTranslatef( 0.f, SCREEN_HEIGHT, 0.f );//从上次的右边 移动到右下边,其中右边是上一次的移动效果,因为没有把模型矩阵重置为单位矩阵
glBegin( GL_QUADS );
glColor3f( 0.f, 0.f, 1.f );
glVertex2f( -SCREEN_WIDTH / 4.f, -SCREEN_HEIGHT / 4.f );
glVertex2f( SCREEN_WIDTH / 4.f, -SCREEN_HEIGHT / 4.f );
glVertex2f( SCREEN_WIDTH / 4.f, SCREEN_HEIGHT / 4.f );
glVertex2f( -SCREEN_WIDTH / 4.f, SCREEN_HEIGHT / 4.f );
glEnd();
glTranslatef( -SCREEN_WIDTH, 0.f, 0.f );//从上次的右下边 移动到正下边
glBegin( GL_QUADS );
glColor3f( 1.f, 1.f, 0.f );
glVertex2f( -SCREEN_WIDTH / 4.f, -SCREEN_HEIGHT / 4.f );
glVertex2f( SCREEN_WIDTH / 4.f, -SCREEN_HEIGHT / 4.f );
glVertex2f( SCREEN_WIDTH / 4.f, SCREEN_HEIGHT / 4.f );
glVertex2f( -SCREEN_WIDTH / 4.f, SCREEN_HEIGHT / 4.f );
glEnd();
glutSwapBuffers();
}
void handleKeys( unsigned char key, int x, int y )
{
if( key == ‘w‘ )
{
gCameraY -= 16.f;
}
else if( key == ‘s‘ )
{
gCameraY += 16.f;
}
else if( key == ‘a‘ )
{
gCameraX -= 16.f;
}
else if( key == ‘d‘ )
{
gCameraX += 16.f;
}
glMatrixMode( GL_MODELVIEW );
glPopMatrix();//弹出栈里的矩阵作为当前矩阵
glLoadIdentity();//重置为单位矩阵
glTranslatef( -gCameraX, -gCameraY, 0.f );//移动位置
glPushMatrix();//压入栈里
}
//其他地方不变