我正在尝试实现一个轨迹球风格的相机。我使用 glm::lookAt 来保持相机指向目标,然后使用方位角/倾角在球体表面周围移动它来旋转视图。
我遇到了一个问题,当方位角接近 90 度时,视图会颠倒过来。
以下是相关代码:
获取投影并查看矩阵。在主循环中运行
void Visual::updateModelViewProjection() { model = glm::mat4(); projection = glm::mat4(); view = glm::mat4(); projection = glm::perspective ( (float)glm::radians(camera.Zoom), (float)width / height, // aspect ratio 0.1f, // near clipping plane 10000.0f // far clipping plane ); view = glm::lookAt(camera.Position, camera.Target, camera.Up); }
鼠标移动事件,用于相机旋转
void Visual::cursor_position_callback(GLFWwindow* window, double xpos, double ypos) { if (leftMousePressed) { ... } if (rightMousePressed) { GLfloat xoffset = (xpos - cursorPrevX) / 4.0; GLfloat yoffset = (cursorPrevY - ypos) / 4.0; camera.inclination += yoffset; camera.azimuth -= xoffset; if (camera.inclination > 89.0f) camera.inclination = 89.0f; if (camera.inclination < 1.0f) camera.inclination = 1.0f; if (camera.azimuth > 359.0f) camera.azimuth = 359.0f; if (camera.azimuth < 1.0f) camera.azimuth = 1.0f; float radius = glm::distance(camera.Position, camera.Target); camera.Position[0] = camera.Target[0] + radius * cos(glm::radians(camera.azimuth)) * sin(glm::radians(camera.inclination)); camera.Position[1] = camera.Target[1] + radius * sin(glm::radians(camera.azimuth)) * sin(glm::radians(camera.inclination)); camera.Position[2] = camera.Target[2] + radius * cos(glm::radians(camera.inclination)); camera.updateCameraVectors(); } cursorPrevX = xpos; cursorPrevY = ypos; }
计算相机方向向量
void updateCameraVectors() { Front = glm::normalize(Target-Position); Right = glm::rotate(glm::normalize(glm::cross(Front, {0.0, 1.0, 0.0})), glm::radians(90.0f), Front); Up = glm::normalize(glm::cross(Front, Right)); }
我很确定这与我计算相机右矢量的方式有关,但我不知道如何补偿。
有没有人遇到过这个?有什么建议么?