理解在 opengl 中翻译相机有问题

Have problem understanding translating the camera in opengl

我无法理解翻译相机。我已经可以成功旋转相机,但我仍然对平移相机感到困惑。我包含了关于如何旋转相机的代码,因为平移和旋转需要使用 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;
    }
}

如果你想通过偏移平移相机,那么你必须将相同的矢量 (glm::vec3 offset) 添加到相机位置 (cameraPos) 和相机目标 (center):

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

当您通过 pitchyaw 角度计算相机的新目标 (center) 时,您必须更新向上矢量 (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 ) 和向上向量(cameraUpup):

glm::vec3 right = glm::cross(front, up);

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

要平移标量 (float trans_x) 和 (trans_y),必须将缩放后的 rightup 矢量添加到相机位置 (cameraPos) 和相机目标 (center):

center    = center    + right * trans_x + up * trans_y;
cameraPos = cameraPos + right * trans_x + up * trans_y;

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

modelViewProjectionMatrix.LookAt(cameraPos, center, cameraUp);