在 opengl 中翻译相机时遇到问题

Have problem understanding translating the camera in opengl

本文关键字:遇到 问题 相机 翻译 opengl      更新时间:2023-10-16

我在理解翻译相机方面遇到问题。我已经可以成功旋转相机,但我仍然对平移相机感到困惑。我包含了关于如何旋转相机的代码,因为平移和旋转需要使用 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轴(从左到右(平移相机,您必须通过向量到目标(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);