OpenGL 使用 Q 和 E 字符移动相机 GLFW 库
Posted
技术标签:
【中文标题】OpenGL 使用 Q 和 E 字符移动相机 GLFW 库【英文标题】:OpenGL use Q and E characters to move camera GLFW libraries 【发布时间】:2021-05-30 17:29:54 【问题描述】:我无法找出正确的命令来添加到此并让 Q 和 E 命令直接上下移动相机。我尝试了很多方法都没有成功。
void processInput(GLFWwindow *window)
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
float cameraSpeed = 2.5 * deltaTime;
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
cameraPos += cameraSpeed * cameraFront;
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
cameraPos -= cameraSpeed * cameraFront;
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
cameraPos -= glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
cameraPos += glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;
【问题讨论】:
大概和 W/S 是一样的,只不过是用cameraUp
而不是cameraFront
。
cameraUp
是否垂直于cameraFront
?
问题解决了吗?请阅读What should I do when someone answers my question?
【参考方案1】:
如果cameraUp
垂直于cameraFront
:
if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS)
cameraPos -= cameraSpeed * cameraUp;
if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS)
cameraPos += cameraSpeed * cameraUp;
如果cameraUp
不(完全)垂直于cameraFront
,则必须计算由cross(cameraFront, cameraUp)
和cameraFront
定义的平面上的法线向量:
glm::vec3 lateral_vector = glm::normalize(glm::cross(cameraFront, cameraUp));
glm::vec3 up_vector = glm::normalize(glm::cross(lateral_vector, cameraFront));
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
cameraPos -= cameraSpeed * cameraFront;
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
cameraPos += cameraSpeed * cameraFront;
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
cameraPos -= cameraSpeed * lateral_vector;
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
cameraPos += cameraSpeed * lateral_vector;
if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS)
cameraPos -= cameraSpeed * up_vector;
if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS)
cameraPos += cameraSpeed * up_vector;
【讨论】:
【参考方案2】:if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS)
gCameraPos -= cameraSpeed * gCameraUp * cameraOffset;
if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS)
gCameraPos += cameraSpeed * gCameraUp * cameraOffset;
【讨论】:
虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高答案的长期价值。谢谢!以上是关于OpenGL 使用 Q 和 E 字符移动相机 GLFW 库的主要内容,如果未能解决你的问题,请参考以下文章
使用 OpenGL 进行正交投影以及如何实现相机或物体在空间中的移动