Reputation: 1660
I am creating 2D game with OpenGL. Everytime I move my object, I have to call glLoadIdentity
, because otherwise all objects will be moved, but glLoadIdentity
also resets glOrtho
call, so basically I ending with something like this:
#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();
}
How should it be done properly, to display, move and rotate objects with glOrtho
enabled?
Upvotes: 1
Views: 1447
Reputation: 162164
but glLoadIdentity also resets glOrtho call, so basically I ending with something like this
glOrtho belongs into the projection matrix, not the modelview matrix. The answer you accepted is not conceptually wrong, but it did miss that part. That part of your code should look like
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();
Upvotes: 6
Reputation: 6526
You need glPushMatrix() and glPopMatrix(). Checkout this tutorial:
http://www.swiftless.com/tutorials/opengl/pop_and_push_matrices.html
Upvotes: 4