我正在使用OpenGL创建2D游戏。每当我移动对象时,我都必须调用glLoadIdentity
,因为否则所有对象都会被移动,但glLoadIdentity
也会重置glOrtho
调用,所以基本上我以这样的结尾结束:
#include <GL/glfw.h>
int main()
{
glfwInit();
glfwOpenWindowHint( GLFW_WINDOW_NO_RESIZE, GL_TRUE );
glfwOpenWindowHint( GLFW_FSAA_SAMPLES, 8 );
glfwOpenWindow( 800, 600, 0, 0, 255, 0, 32, 0, GLFW_WINDOW );
glfwSetWindowTitle( "title" );
glfwSwapInterval( 1 ); // also known as 'vsync'
glfwEnable( GLFW_KEY_REPEAT );
//glfwDisable( GLFW_MOUSE_CURSOR );
glOrtho(0.0, 1024, 768, 0, -1.0, 1.0);
glMatrixMode( GL_MODELVIEW );
while( !glfwGetKey( GLFW_KEY_ESC ) )
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glOrtho(0.0, 1024, 768, 0, -1.0, 1.0);
glTranslatef( 100, 0, 0 );
glColor3f(0.5f,0.5f,1.0f);
glBegin(GL_POLYGON);
glVertex2f(100, 100);
glVertex2f(100, 250);
glVertex2f(250, 250);
glVertex2f(250, 100);
glEnd();
glLoadIdentity();
glOrtho(0.0, 1024, 768, 0, -1.0, 1.0);
glRotatef( 25,0,0,1);
glBegin(GL_POLYGON);
glVertex2f(300, 300);
glVertex2f(300, 450);
glVertex2f(450, 450);
glVertex2f(450, 300);
glEnd();
glFlush();
glfwSwapBuffers();
}
glfwTerminate();
}
如何正确完成,显示,移动和旋转启用了glOrtho
的对象?
答案 0 :(得分:5)
但glLoadIdentity也会重置glOrtho调用,所以基本上我以这样的结尾结束
glOrtho属于投影矩阵,而不属于模型视图矩阵。你接受的答案在概念上并没有错,但确实错过了那一部分。您的代码部分应该看起来像
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1024, 768, 0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef( 100, 0, 0 );
glColor3f(0.5f,0.5f,1.0f);
glBegin(GL_POLYGON);
glVertex2f(100, 100);
glVertex2f(100, 250);
glVertex2f(250, 250);
glVertex2f(250, 100);
glEnd();
glLoadIdentity();
glRotatef( 25,0,0,1);
glBegin(GL_POLYGON);
glVertex2f(300, 300);
glVertex2f(300, 450);
glVertex2f(450, 450);
glVertex2f(450, 300);
glEnd();
glFlush();
glfwSwapBuffers();
答案 1 :(得分:4)
你需要glPushMatrix()和glPopMatrix()。查看本教程:
http://www.swiftless.com/tutorials/opengl/pop_and_push_matrices.html