使用 gluLookAt 的问题

Trouble with the use of gluLookAt

我已经查看了多个关于此的问题,包括 this 一个。我想要的是一个人俯视走廊,在人的侧视图上看后墙和左右墙。这是我的代码:

初始化

float lookAtX = 0, lookAtY = 0, lookAtZ = -2.5, posX = 0, posY = 0, posZ = 0;

绘图

    glEnable(GL_DEPTH_TEST);
    glMatrixMode(GL_MODELVIEW);

    gluLookAt(
        posX, posY, posZ, 
        lookAtX, lookAtY, lookAtZ, 
        0, 0, 1
    );
    // Back
    glBegin(GL_POLYGON);
    glColor3f(255, 0, 0); // Red
    glVertex3f(-2.5, -2.5, 2.5);
    glVertex3f(2.5, 2.5, 2.5);
    glVertex3f(2.5, -2.5, 2.5);
    glVertex3f(-2.5, -2.5, 2.5);
    glEnd();

    // Left
    glBegin(GL_POLYGON);
    glColor3f(0, 255, 0); // Green
    glVertex3f(-2.5, 2.5, 2.5);
    glVertex3f(-2.5, 2.5, -2.5);
    glVertex3f(-2.5, -2.5, 2.5);
    glVertex3f(-2.5, -2.5, -2.5);
    glEnd();

    // Right
    glBegin(GL_POLYGON); 
    glColor3f(0, 0, 255); // Yellow
    glVertex3f(2.5, 2.5, 2.5);
    glVertex3f(2.5, 2.5, -2.5);
    glVertex3f(2.5, -2.5, 2.5);
    glVertex3f(2.5, -2.5, -2.5);
    glEnd();

    glFlush();
    window.pushGLStates();

我确信外部代码是正确的,因为我有另一段具有相同骨架的代码。我也相信这会奏效......但我想它没有 xD。为什么有黑屏,为什么不显示墙壁?感谢您花时间阅读本文

首先要注意的是,glBegin/glEnd 序列的绘图已被弃用多年。 阅读 Fixed Function Pipeline and see Vertex Specification and Shader 了解最先进的渲染方式。


不管怎样,你得设置一个透视投影矩阵。但请注意,像 gluLookAt and gluPerspective 这样的操作不仅定义了一个矩阵。
此操作定义一个矩阵并将矩阵堆栈上的当前矩阵乘以新矩阵。这意味着您必须先通过单位矩阵初始化矩阵上的矩阵。这可以通过 glLoadIdentity 来完成。

使用gluPerspective to set the perspective projection on the projection matrix stack - glMatrixMode( GL_PROJECTION ):

glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective( 90.0f, view_width / view_height, 0.1f, 10.0f );

当你设置视图矩阵时,你必须改变视角并朝"corridor"的方向看。因为你看 z 轴,向上矢量必须是 (0, 1, 0):

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
float lookAtX = 0, lookAtY = 0, lookAtZ = 0, posX = 0, posY = 0, posZ = -5;
gluLookAt( posX, posY, posZ, lookAtX, lookAtY, lookAtZ, 0, 1, 0 );

你的顶点坐标终于混合了。像这样更改它:

// Back
glBegin(GL_POLYGON);
glColor3ub(255, 0, 0); // Red
glVertex3f(-2.5, -2.5, 2.5);
glVertex3f(-2.5,  2.5, 2.5);
glVertex3f( 2.5,  2.5, 2.5);
glVertex3f( 2.5, -2.5, 2.5);
glEnd();

// Left
glBegin(GL_POLYGON);
glColor3ub(0, 255, 0); // Green
glVertex3f(-2.5,  2.5,  2.5);
glVertex3f(-2.5,  2.5, -2.5);
glVertex3f(-2.5, -2.5, -2.5);
glVertex3f(-2.5, -2.5,  2.5);
glEnd();

// Right
glBegin(GL_POLYGON); 
glColor3ub(0, 0, 255); // Blue
glVertex3f(2.5,  2.5,  2.5);
glVertex3f(2.5,  2.5, -2.5);
glVertex3f(2.5, -2.5, -2.5);
glVertex3f(2.5, -2.5,  2.5);
glEnd();

预览: