简体   繁体   English

完成所有绘图代码后,我是否需要重复glOrtho调用?

[英]Do I need to repeat glOrtho call after all my drawing code?

I am creating 2D game with OpenGL. 我正在使用OpenGL创建2D游戏。 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: 每次移动对象时,都必须调用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();
}

How should it be done properly, to display, move and rotate objects with glOrtho enabled? 如何在启用glOrtho情况下正确地显示,移动和旋转对象?

but glLoadIdentity also resets glOrtho call, so basically I ending with something like this 但是glLoadIdentity也会重置glOrtho调用,所以基本上我以这样的结尾

glOrtho belongs into the projection matrix, not the modelview matrix. glOrtho属于投影矩阵,而不属于modelview矩阵。 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();

You need glPushMatrix() and glPopMatrix(). 您需要glPushMatrix()和glPopMatrix()。 Checkout this tutorial: 查看本教程:

http://www.swiftless.com/tutorials/opengl/pop_and_push_matrices.html http://www.swiftless.com/tutorials/opengl/pop_and_push_matrices.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM