OpenGL第四節:滾動和矩陣棧
頭文件不變
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();//壓入棧裏
}
//其他地方不變
OpenGL第四節:滾動和矩陣棧