【问题标题】:Understanding OpenGL glPushMatrix and glPopMatrix了解 OpenGL glPushMatrix 和 glPopMatrix
【发布时间】:2021-06-03 00:19:14
【问题描述】:

我是 OpenGL 新手,尝试渲染两个对象,但只有一个对象应该旋转。我从here 了解到,我可以使用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...
}

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

【问题讨论】:

    标签: c++ opengl opengl-compat


    【解决方案1】:

    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();
    }
    

    【讨论】:

    • 是的,这是一个愚蠢的错误:(但我已经解决了这个问题,他们没有动
    • 抱歉...我只是想确保我一次只提出一个问题。不过,您的新答案解决了我的问题,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    • 2017-04-14
    相关资源
    最近更新 更多