inline void Revolve(float fwdDist, float yawDifDeg, float pitchDifDeg) { float pitchDifRad = glm::radians(-pitchDifDeg); float yawDifRad = glm::radians(-yawDifDeg); constexpr float PITCH_LIMIT = glm::radians(60.f); pitchRad += pitchDifRad; // avoid deadlock if (pitchRad > PITCH_LIMIT) pitchRad = PITCH_LIMIT; else if (pitchRad < -PITCH_LIMIT) pitchRad = -PITCH_LIMIT; yawRad += yawDifRad; // avoid reaching float limit if (yawRad > glm::pi<float>()) yawRad -= 2 * glm::pi<float>(); else if (yawRad < -glm::pi<float>()) yawRad += 2 * glm::pi<float>(); auto center = pos + fwdDist * forward; { float cy = cosf(yawRad), sy = sinf(yawRad); float cp = cosf(pitchRad), sp = sinf(pitchRad); forward.x = cp * cy, forward.y = sp, forward.z = -cp * sy; forward = glm::normalize(forward); } right = glm::normalize(glm::cross(forward, worldUp)); up = glm::normalize(glm::cross(right, forward)); pos = center - fwdDist * forward; view[0][0] = right.x; view[1][0] = right.y; view[2][0] = right.z; view[0][1] = up.x; view[1][1] = up.y; view[2][1] = up.z; view[0][2] = -forward.x; view[1][2] = -forward.y; view[2][2] = -forward.z; view[3][0] = -glm::dot(right, pos); view[3][1] = -glm::dot(up, pos); view[3][2] = glm::dot(forward, pos); view[3][3] = 1.f; view[0][3] = view[1][3] = view[2][3] = 0; } 使用该方法实现当鼠标按下且同时移动时,相机旋转
时间: 2024-04-14 13:28:05 浏览: 208
要实现当鼠标按下且同时移动时相机旋转,你可以使用 GLFW 库的鼠标移动回调函数来获取鼠标的偏移量,然后根据偏移量来更新相机的旋转角度。以下是一个示例代码,说明如何在上述方法中实现该功能:
首先,在你的代码中添加一个全局变量来追踪鼠标的上一次位置:
```cpp
double lastX = 0.0;
double lastY = 0.0;
bool firstMouse = true;
```
然后,在你的 GLFW 鼠标移动回调函数中添加以下代码:
```cpp
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
if (firstMouse)
{
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
float xoffset = xpos - lastX;
float yoffset = lastY - ypos; // 注意这里的坐标系,需要反过来计算
lastX = xpos;
lastY = ypos;
// 根据偏移量更新相机的旋转角度
Revolve(1.0f, xoffset, yoffset);
}
```
在这段代码中,我们首先检查 `firstMouse` 变量,如果是第一次移动鼠标,则将当前鼠标位置赋值给 `lastX` 和 `lastY`。然后,我们计算当前鼠标位置与上一次鼠标位置的偏移量 `xoffset` 和 `yoffset`。最后,我们将当前鼠标位置更新为上一次鼠标位置,并调用 `Revolve` 方法来根据偏移量更新相机的旋转角度。
记得在 `main` 函数中设置鼠标移动回调函数:
```cpp
glfwSetCursorPosCallback(window, mouse_callback);
```
这样,当鼠标按下且同时移动时,`mouse_callback` 函数将被触发,并更新相机的旋转角度。
阅读全文