首页 > 解决方案 > 了解 OpenGL glPushMatrix 和 glPopMatrix

问题描述

我是 OpenGL 新手并试图渲染两个对象,但只有一个对象应该旋转。我从这里了解到,我只能在一个对象上使用glPushMatrixglPopMatrix应用旋转,但我的不起作用。

这是我的代码:

void renderObjs() {
    //glPushMatrix();
    drawPyramid(0, 0.7, 0, 0.289, 0, 0.167, -0.289, 0, 0.167, 0, 0, -0.33); // a function to draw triangles
    //glPopMatrix();

    glPushMatrix();
    glRotatef(0.3f, 1.f, 1.f, 1.f);
    drawPyramid(0 - 0.5, 0.7 - 0.5, 0 - 0.5, 0.289 - 0.5, 0 - 0.5, 0.167 - 0.5, -0.289 - 0.5, 0 - 0.5, 0.167 - 0.5, 0 - 0.5, 0 - 0.5, -0.33 - 0.5);
    glPopMatrix();
}

int main() {
    // some initialization
    ...codes here...

    while (!glfwWindowShouldClose(window))
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glMatrixMode(GL_MODELVIEW);

        renderObjs();

        glfwSwapBuffers(window);                      
        glfwPollEvents();
    }

    // other useful functions
    ...codes here...
}

但我的金字塔都没有旋转。为什么会这样?我是否以错误的方式使用glPushMatrixand ?glPopMatrix

标签: c++openglopengl-compat

解决方案


矩阵变换操作,例如glRotatef,指定一个矩阵并将当前矩阵乘以新矩阵。glPushMatrix将当前矩阵推入矩阵堆栈。glPopMatrix从矩阵堆栈中弹出一个矩阵,并通过弹出的矩阵设置当前矩阵。角度的单位glRotate是度:

glPushMatrix();
glRotatef(30.0f, 1.f, 1.f, 1.f);
drawPyramid(0 - 0.5, 0.7 - 0.5, 0 - 0.5, 0.289 - 0.5, 0 - 0.5, 0.167 - 0.5, -0.289 - 0.5, 0 - 0.5, 0.167 - 0.5, 0 - 0.5, 0 - 0.5, -0.33 - 0.5);
glPopMatrix();

如果要连续旋转物体,则需要在每张图像中增加旋转角度:

float angle = 0.0f;

void renderObjs() {
    //glPushMatrix();
    drawPyramid(0, 0.7, 0, 0.289, 0, 0.167, -0.289, 0, 0.167, 0, 0, -0.33); // a function to draw triangles
    //glPopMatrix();

    glPushMatrix();
   
    glRotatef(angle, 1.f, 1.f, 1.f);
    angle += 0.1f   

    drawPyramid(0 - 0.5, 0.7 - 0.5, 0 - 0.5, 0.289 - 0.5, 0 - 0.5, 0.167 - 0.5, -0.289 - 0.5, 0 - 0.5, 0.167 - 0.5, 0 - 0.5, 0 - 0.5, -0.33 - 0.5);
    glPopMatrix();
}

推荐阅读