gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:43:28 25 4
gpt4 key购买 nike

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

最佳答案

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

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

当您通过俯仰偏航角度计算相机的新目标(center)时,您必须更新相机的向上 vector (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 计算向右的 vector 到目标的 vector (front)和向上 vector (cameraUpup):

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

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

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

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

使用被操纵的 vector 来设置 View 矩阵:

modelViewProjectionMatrix.LookAt(cameraPos, center, cameraUp);

关于c++ - 理解在 opengl 中翻译相机有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58264255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com