1     //摄像机的位置
 2     //不要忘记z轴是从屏幕指向你的,如果我们希望摄像机向后移动,我们就沿着z轴的正方向移动
 3     glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, 3.0f);    
 4     glm::vec3 cameraTarget = glm::vec3(0.0f, 0.0f, 0.0f);
 5     glm::vec3 cameraDirection = glm::normalize(cameraPos - cameraTarget);//这个方向是物体指向摄像机的方向(方向向量)
 6 
 7     //右轴,右向量(right vector>,它代表摄像机空间的x轴的正方向,
 8     //定义方法:先定义一个上向量(up vector),接下来把上向量的上一步得到的方向向量进行叉乘
 9     glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f);
10     glm::vec3 cameraRight = glm::normalize(glm::cross(up, cameraDirection));
11 
12     //上轴,将右轴和方向向量进行叉乘
13     glm::vec3 cameraUp = glm::cross(cameraDirection, cameraRight);
14 
15 
16     //lookAt矩阵
17     //我们只需提供一个摄像机位置,目标物体位置,和一个上向量,glm::lookAt就会为我们自动生成一个lookAt矩阵,即一个观察矩阵
18     glm::mat4 view;
19     view = glm::lookAt(glm::vec3(0.0f, 0.0f, 3.0f),
20     glm::vec3(0.0f, 0.0f, 0.0f),
21     glm::vec3(0.0f, 1.0f, 0.0f));

摄像机自动移动

1 float radius = 10.0f;
2         float camX = sin(glfwGetTime()) * radius;
3         float camZ = cos(glfwGetTime())* radius;
4         glm::mat4 view;
5         view = glm::lookAt(glm::vec3(camX, 0.0, camZ),
6             glm::vec3(0.0f, 0.0f, 0.0f),
7             glm::vec3(0.0f, 1.0f, 0.0f));
8         glUniformMatrix4fv(glGetUniformLocation(ourShader.ID, "view"), 1, GL_FALSE, glm::value_ptr(view));

用WASD控制摄像机的前后左右移动

 1 glm::vec3 cameraPos = glm::vec3(0.0, 0.0f, 5.0f);
 2 glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f);
 3 glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f);
 4 glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);
 5         glUniformMatrix4fv(glGetUniformLocation(ourShader.ID, "view"), 1, GL_FALSE, glm::value_ptr(view));
 6 void processInput(GLFWwindow* window)
 7 {
 8 
 9     float cameraSpeed = 0.5f;
10     if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
11         cameraPos += cameraSpeed * cameraFront;
12     if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
13         cameraPos -= cameraSpeed * cameraFront;
14     if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
15         cameraPos -= glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;
16     if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
17         cameraPos += glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;
18 
19 }