如何在 OpenGL 中更改视角?

Posted

技术标签:

【中文标题】如何在 OpenGL 中更改视角?【英文标题】:How do I change the viewing angle in OpenGL? 【发布时间】:2019-07-16 22:03:08 【问题描述】:

我需要创建一个 3d 立方体,到目前为止,我已经创建了所有顶点,但是当我运行程序时,我只能从一个脸,所以它看起来像一个正方形。我想知道如何从上方查看我的立方体,这样我就可以检查它是否真的看起来像我想要的那样。

我使用 glVertex3f 创建了 24 个顶点,但就像我说的那样,我无法判断它是否是立方体,因为我无法从默认角度以外的角度查看它。

我尝试下载 GLM,但我很困惑如何使用它来改变视角。

glEnable(GL_DEPTH_TEST);
    // Loop until the user closes the window
    while (!glfwWindowShouldClose(window))
    
        // Render here
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glBegin(GL_QUADS);
        glColor3f(0.0f, 1.0f, 0.0f);
        glVertex3f(0.5f, 0.5f, 0.5f);
        glVertex3f(-0.5f, 0.5f, 0.5f);
        glVertex3f(-0.5f, -0.5f, 0.5f);
        glVertex3f(0.5f, -0.5f, 0.5f);

        ... // Repeating drawing the vertices for each vertex of the cube

        glEnd();

        // Swap front and back buffers
        glfwSwapBuffers(window);

        // Poll for and process events
        glfwPollEvents();
    

没有错误消息,但我不知道它是否是立方体。

【问题讨论】:

我建议你阅读投影矩阵。每个基本的 OpenGL 教程都有一个渲染立方体的示例。 【参考方案1】:
    // Render here
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // need the window width & height to compute aspect ratio
    int width, height;
    glfwGetWindowSize(window, &width, &height);

    // set up the camera projection (if you haven't done this in init)
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45.0f, float(width) / height, 0.1f, 100.0f);

    // set camera position & orientation
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(1, 1, -3, //< eye position
              0, 0, 0,  //< aim position
              0, 1, 0); //< up direction

    // now draw stuff
    glBegin(GL_QUADS);
    glEnd();

【讨论】:

完美!看起来我确实正确地制作了立方体,我只是看不到它,因为我从 z 方向看它,它只显示了一张脸。非常感谢!

以上是关于如何在 OpenGL 中更改视角?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 OpenGL 中更改旋转中心

如何在 OpenGL/Glut 中更改鼠标光标的位置?

OpenGL获取像素的原始3d坐标

如何在 MacOS 上使用 QGLFormat 更改 OpenGL 版本?

如何在中心更改opengl的Point坐标

(转)使用OpenGL显示图像运用投影与相机视角