# OpenGL-摄像机

## 概念

OpenGL本身没有摄像机(Camera)的概念，但我们可以通过把场景中的所有物体往 相反方向移动 的方式来模拟出摄像机，产生一种 我们在移动的感觉，而不是场景在移动

## 摄像机/观察空间

• 观察矩阵把所有的世界坐标变换为相对于摄像机位置与方向的观察坐标。

### 摄像机位置

glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, 3.0f);


### 摄像机方向

glm::vec3 cameraTarget = glm::vec3(0.0f, 0.0f, 0.0f);
glm::vec3 cameraDirection = glm::normalize(cameraPos - cameraTarget);


### 右轴

glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f);


### 上轴

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


## 自由移动

glm::vec3 cameraPos   = glm::vec3(0.0f, 0.0f,  3.0f);
glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f);
glm::vec3 cameraUp    = glm::vec3(0.0f, 1.0f,  0.0f);

view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);


void processInput(GLFWwindow *window)
{
...
float cameraSpeed = 0.05f; // adjust accordingly
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;
}


## 欧拉角

direction.y = sin(glm::radians(pitch)); // 注意我们先把角度转为弧度


## 移动

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;

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

yaw   += xoffset;
pitch += yoffset;

if(pitch > 89.0f)
pitch = 89.0f;
if(pitch < -89.0f)
pitch = -89.0f;

glm::vec3 front;
cameraFront = glm::normalize(front);
}


## 缩放

void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
if(fov >= 1.0f && fov <= 45.0f)
fov -= yoffset;
if(fov <= 1.0f)
fov = 1.0f;
if(fov >= 45.0f)
fov = 45.0f;
}


06-22 2733

09-26 481
12-22 161
10-21 105
12-18 547
02-13 2703
09-27 1437
04-15 932
12-10 8万+
06-08 6333
12-25
12-14 1万+