# 摄像机/观察空间

## 程序执行效果

### 摄像机代码

// 摄像机
view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);
ourShader.setMat4("view", view);


glm::lookAt(eye, center, up)

eye实际上就是摄像机的位置
center就是摄像机的方向
up就是上轴

eye -> cameraPos
center -> cameraPos + cameraFront
up -> cameraUp

1、cameraPos:
vec3(0.0, 0.0, 3.0);

2、cameraFront:
vec3(0.0, 0.0, -1.0); // z 轴相反的方向为摄像机向前

3、cameraPos - cameraFront:
v1 = vec3(x: 0.0, y: 0.0, z: 3.0) , v2 = vec3(x: 0.0, y: 0.0, z: -1.0)
(v1) + (-v2) = (0.0, 0.0, 3.0 + -0.0, -0.0, 1.0)
(0.0, 0.0, 4.0)

cameraPos - cameraFront = (0.0, 0.0, 2.0)

4、cameraDirection = glm::normalize(cameraPos + cameraFront) // 也可以不用这样，直接将cameraPos + cameraFront作为方向

vector normalize = v|v| (v≠0)
carmeraDirection = (0.0, 0.0, 1.0)

5、cameraUp

glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f);
glm::vec3 cameraRight = glm::normalize(glm::cross(up, cameraDirection));

glm::vec3 cameraUp = glm::cross(cameraDirection, cameraRight);

cameraUp = cross(cameraDirection, cross(up, cameraDirection))


glm::cross是求向量的叉积(向量乘法的叉乘)的：

cameraUp = (0, 1, 0) // Y axis its Up axis

glm::vec3 Pos = glm::vec3(0.0f, 0.0f, 3.0f);
glm::vec3 Target = glm::vec3(0.0f, 0.0f, 0.0f);
glm::vec3 Direction = glm::normalize(Pos - Target);
glm::vec3 Up = glm::vec3(0.0f, 1.0f, 0.0f);
glm::vec3 Right = glm::normalize(glm::cross(Up, Direction));
glm::vec3 CamUp = glm::cross(Direction, Right);


6、得到了摄像机的向量后，我们通过LookAt Matrix来求得View Matrix：

R -> Right Vector右向量
U -> Up 是上向量(Up axis)
D -> Direction 方向向量
P -> Camera Position 摄像机的位置(空间中的点坐标)

## 摄像机的移动

FPS游戏中我们通常用WSAD，来控制前进、后退、左移、右移。

front(position) = front(position) + speed * position

back(position) = back(position) - speed * position

left(position) = left(position) - normalize(cross(front, up)) * speed;

right(position) = right(position) + normalize(cross(front, up)) * speed;

GLfloat cameraSpeed = 2.5 * deltaTime;
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
cameraPos += cameraSpeed * cameraFront;
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
cameraPos -= cameraSpeed * cameraFront;
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
cameraPos -= glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
cameraPos += glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;


## 欧拉角与摄像机鼠标控制视野转动

### 欧拉角

PI派约等于：3.14159265359

sin(pitch * PI / 180.0)

direction.y = sin(glm::radians(pitch));


direction.x = cos(glm::radians(pitch));
direction.z = cos(glm::radians(pitch));


// 译注：direction代表摄像机的前轴(Front)，这个前轴是上面图中第一个展示
direction.x = cos(glm::radians(pitch)) * cos(glm::radians(yaw)); 第二个摄像机的方向向量是相反的
direction.y = sin(glm::radians(pitch));
direction.z = cos(glm::radians(pitch)) * sin(glm::radians(yaw));


## 全部代码

08-11 687
07-10 921
04-06 7万+
11-27 591
03-19
09-01 599
07-09 1235
01-29 1217
03-25 2万+
05-18 1815
10-26 117
05-25 774
07-01 498
12-22 161
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客