创建一个围绕对象OpenGL C ++旋转的相机

时间:2014-12-09 17:03:51

标签: c++ opengl rotation

我在本教程结束时进行练习: Link

但是我坚持"创建一个围绕对象旋转的相机"

( position = ObjectCenter + ( radius * cos(time), height, radius * sin(time) ) );

我已使用上面提供的代码创建以下轮播

GLfloat radius = 10.0f;
position = glm::vec3(0.0f,0.0f,0.0f) + glm::vec3(radius * cos(glfwGetTime()), 0.0f, radius * sin(glfwGetTime()));

使用此场景会在距离10处旋转(0,0,0),我认为它是立方体的中心,但事实并非如此,因此立方体经常像场景一样闪过窗口。旋转。

那么我究竟如何找到对象中心?当我绘制立方体时,我不会从代码中理解我告诉它的中心位置。

作为参考,初始位置vec是

glm::vec3 position = glm::vec3( 0, 0, 5 );

1 个答案:

答案 0 :(得分:1)

最简单的方法是在 controls.cpp 中添加以下内容,并在 controls.hpp

中声明它
glm::vec3 *getPosition(){
    return &position;
}
void setPosition(glm::vec3 var){
    position = var;
}

然后你只需要在主循环的开头声明以下变量:

float rotCamera = 0.0f;
glm::vec3 origPos = *getPosition();

并在主循环中的 glfwPollEvents(); 之后添加以下行:

// Swap buffers
glfwSwapBuffers(window);
glfwPollEvents();

//To rotate the camera through the object
if (glfwGetKey( window, GLFW_KEY_C ) == GLFW_PRESS){
    rotCamera += 0.01;
    glm::vec3 rot(cos(rotCamera) * 10.0 - origPos.x,  0, sin(rotCamera) * 10.0 - origPos.z);
    setPosition(origPos + rot);
}

最后,如果您希望相机始终查看多维数据集,则必须将controlsAt从controls.cpp更改为始终显示为(0,0,0):

ViewMatrix       = glm::lookAt(position,           // Camera is here
                                glm::vec3( 0, 0, 0 ), //To look always to the cube
                                up                  // Head is up (set to 0,-1,0 to look upside-down)
                           );
相关问题