了解在opengl中翻译相机的问题

问题描述 投票:1回答:1

我在理解相机的翻译时遇到麻烦。我已经可以成功旋转相机了,但是我仍然对平移相机感到困惑。我包含有关如何旋转相机的代码,因为平移和旋转需要使用lookat函数。作业说平移相机意味着眼睛和中心都应该移动相同的量。我知道我可以更改lookat函数中的参数以实现此目的。

lookat函数的定义如下:

Lookat(cameraPos, center, up)
glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, 10.0f);
glm::vec3 center(0.0f, 0.0f, 0.0f);
glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f);

modelViewProjectionMatrix.Perspective(glm::radians(fov), float(width) / float(height), 0.1f, 100.0f);
modelViewProjectionMatrix.LookAt(cameraPos, center, cameraUp);
void CursorPositionCallback(GLFWwindow* lWindow, double xpos, double ypos)
{
    int state = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT);

    if (state == GLFW_PRESS)
    {
        if (firstMouse)
        {
          lastX = xpos;
          lastY = ypos;
          firstMouse = false;
        }

        float xoffset = xpos - lastX;
        float yoffset = lastY- ypos; 
        lastX = xpos;
        lastY = ypos;

        yaw += xoffset;
        pitch += yoffset;

        glm::vec3 front;
        front.x = center[0] + 5.0f*cos(glm::radians(yaw)) * cos(glm::radians(pitch));
        front.y = center[1] + 5.0f*sin(glm::radians(pitch));
        front.z = center[1] + 5.0f*sin(glm::radians(yaw)) * cos(glm::radians(pitch));
        cameraPos = front;
    }
}
c++ opengl glm-math
1个回答
1
投票

[如果要平移摄影机偏移量,则必须将相同的向量(glm::vec3 offset)添加到摄影机位置(cameraPos)和摄影机目标(center):

center    = center    + offset;
cameraPos = cameraPos + offset;

[当您以centerpitch角计算摄像机的新目标(yaw)时,也必须更新摄像机的向上矢量(cameraUp):

glm::vec3 front(
    cos(glm::radians(pitch)) * cos(glm::radians(yaw)),
    sin(glm::radians(pitch)),
    cos(glm::radians(pitch)) * sin(glm::radians(yaw))
);

glm::vec3 up(
    -sin(glm::radians(pitch)) * cos(glm::radians(yaw)),
     cos(glm::radians(pitch)),
    -sin(glm::radians(pitch)) * sin(glm::radians(yaw))
);

cameraPos = center + front * 5.0f;
cameraUp  = up;

要在视空间中沿x轴(从左到右)平移相机,您必须通过将矢量的Cross product移至目标(front)和向上的矢量([[ C0]或cameraUp):

up

视图空间中的y轴(从下到上)是向上矢量。

要转换标量(glm::vec3 right = glm::cross(front, up); )和(float trans_x),必须将缩放后的trans_yright向量添加到摄像机位置(up)和摄像机目标(cameraPos ):

center

使用操纵向量设置视图矩阵:

center    = center    + right * trans_x + up * trans_y;
cameraPos = cameraPos + right * trans_x + up * trans_y;
© www.soinside.com 2019 - 2024. All rights reserved.