前言:该系列教程主要参考自网站www.opengl-tutorial.org,基于开源GUI框架imgui v1.61实现,imgui自带的例子里面直接集成了glfw+gl3w环境,本系列教程将gl3w换成了glew,glew具体环境配置可参考:OpenGL环境配置教程:VS2012 + GLEW + GLFW + GLM。
教程目录(持续更新中):
现代OpenGL教程(一):绘制三角形(ImGui+OpenGL3.3)
现代OpenGL教程(二):矩阵变换(ImGui+OpenGL3.3)
现代OpenGL教程(三):绘制彩色立方体(ImGui+OpenGL3.3)
现代OpenGL教程(四):立方体纹理贴图(ImGui+OpenGL3.3)
现代OpenGL教程(五):obj模型加载(ImGui+OpenGL3.3)
现代OpenGL教程(六):鼠标和键盘(ImGui+OpenGL3.3)
现代OpenGL教程(七):基础光照——颜色(ImGui+OpenGL3.3)
现代OpenGL教程(八):基础光照——Phong光照模型(ImGui+OpenGL3.3)
现代OpenGL教程(九):基础光照——材质(ImGui+OpenGL3.3)
本节教程在上一节(现代OpenGL教程(五):obj模型加载(imgui+OpenGL3.3))的基础上,增加了鼠标和键盘控制视图的功能。完整代码下载地址:https://github.com/maijiaquan/blog-code/tree/master/opengl-control
运行效果
![](https://i-blog.csdnimg.cn/blog_migrate/7a45e46b3775de99ff4dbc6d57f9a9ee.gif)
第一步:鼠标和键盘控制相机view矩阵
glm::mat4 GetView()
{
static double lastTime = glfwGetTime();
double currentTime = glfwGetTime();
float deltaTime = float(currentTime - lastTime);
// Get mouse position
if (canMouseRotate)
{
horizontalAngle -= mouseSpeed * ImGui::GetIO().MouseDelta.x;
verticalAngle -= mouseSpeed * ImGui::GetIO().MouseDelta.y;
}
// Direction : Spherical coordinates to Cartesian coordinates conversion
glm::vec3 direction(
cos(verticalAngle) * sin(horizontalAngle),
sin(verticalAngle),
cos(verticalAngle) * cos(horizontalAngle));
// Right vector
glm::vec3 right = glm::vec3(
sin(horizontalAngle - 3.14f / 2.0f),
0,
cos(horizontalAngle - 3.14f / 2.0f));
// Up vector
glm::vec3 up = glm::cross(right, direction);
// Move forward
if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS)
{
position += direction * deltaTime * speed;
}
// Move backward
if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS)
{
position -= direction * deltaTime * speed;
}
// Strafe right
if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS)
{
position += right * deltaTime * speed;
}
// Strafe left
if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS)
{
position -= right * deltaTime * speed;
}
float FoV = initialFoV ;
glm::mat4 ViewMatrix = glm::lookAt(
position, // Camera is here
position + direction, // and looks here : at the same position, plus "direction"
up // Head is up (set to 0,-1,0 to look upside-down)
);
lastTime = currentTime;
return ViewMatrix;
}
第二步:将view矩阵传给OpenGL
glm::mat4 ViewMatrix = GetView();
glm::mat4 MVP = Projection * ViewMatrix * Model;