我正在开发一个 FPS 风格的相机来使用 OpenGL 在我的 3D 场景中飞行。我将 GLM 用于数学,并使用鼠标移动在 x 轴和 y 轴上使用 glm::rotate 计算方向向量。我有一个静态的向上向量,因为我可以在水平轴上扫射并且不需要任何滚动。
但是,当我朝负 z 方向前进并最终到达场景的中心点 (z=0) 时,垂直相机翻转(y 方向)。向下移动鼠标现在将导致向上运动。方向向量的计算方式应该如此,所以我猜它与 glm::lookAt 如何计算其视图矩阵有关?
以下是相关代码:
// Player movement
glm::vec3 position(0.0f, 0.0f, 5.0f);
glm::vec3 direction(0.0f, 0.0f, -1.0f);
glm::vec3 up(0.0f, 1.0f, 0.0f);
float speed = 0.05f;
bool warped = false;
...
void render()
{
...
view = glm::lookAt(position, position + direction, up);
glUniformMatrix4fv(glGetUniformLocation(basicShader.shaderProgram, "view"), 1, GL_FALSE, glm::value_ptr(view));
...
}
void handleKeyboard()
{
float speed = 0.05f;
if(keys['w'])
position += speed * direction;
if(keys['s'])
position -= speed * direction;
if(keys['a'])
position -= speed * glm::cross(direction, up);
if(keys['d'])
position += speed * glm::cross(direction, up);
if(keys['q'])
exit(1);
}
// Set with following callbacks:
// glutMotionFunc(mouse);
// glutPassiveMotionFunc(mouse);
void mouse(int x, int y)
{
if(!warped)
{
float mouseSensitivity = 15.0f;
float horizontal = (width / 2) - x;
float vertical = (height / 2) - y;
horizontal /= mouseSensitivity;
vertical /= mouseSensitivity;
direction = glm::rotate(direction, horizontal, glm::vec3(0.0f, 1.0f, 0.0f));
direction = glm::rotate(direction, vertical, glm::vec3(1.0f, 0.0f, 0.0f));
warped = true;
glutWarpPointer((width / 2), (height / 2));
}
else
warped = false;
}