OpenGL随笔十三 opengl 用鼠标和键盘的输入控制相机移动

一、控制相机的视角
//禁用光标
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
//注册鼠标事件回调函数
glfwSetCursorPosCallback(window, mouse_callback);

void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
if (firstMouse)
{
lastX = xpos;
lastY = ypos;
firstMouse = false;
}

float xoffset = xpos - lastX;
float yoffset = ypos - lastY;
lastX = xpos;
lastY = ypos;

float sensitivity = 0.05;
xoffset *= sensitivity;
yoffset *= sensitivity;

camera.ProcessMouseMovement(xoffset, yoffset);

}

void Camera::ProcessMouseMovement(float offsetX, float offsetY)
{
Pitch += offsetY0.01;
Pitch = Pitch > 89.0f ? 89.0f : Pitch;
Yaw += offsetX
0.01;
Yaw = Yaw > 89.0f ? 89.0f : Yaw;
UpdateCameraVectors();
}

void Camera::UpdateCameraVectors()
{
Forward.x = glm::cos(Pitch) * glm::sin(Yaw);
Forward.y = glm::sin(Pitch);
Forward.z = glm::cos(Pitch) * glm::cos(Yaw);
Right = glm::normalize(glm::cross(Forward, WorldUp));
Up = glm::normalize(glm::cross(Forward, Right));
}

二、控制相机的远近
void processInput(GLFWwindow* window) {
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) {
glfwSetWindowShouldClose(window, true);
}
else if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) {
camera.speedZ = 1.0f;
}
else if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) {
camera.speedZ = -1.0f;
}
else {
camera.speedZ = .0f;
}
}

void Camera::UpdateCameraPos()
{
Position += Forward * speedZ * 0.01f;
}

Git链接: link.

OpenGL入门完整代码.

发布了25 篇原创文章 · 获赞 0 · 访问量 315
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览