학습을 위해 참고한 사이트
https://learnopengl.com/Getting-started/Camera
LearnOpenGL - Camera
Camera Getting-started/Camera In the previous chapter we discussed the view matrix and how we can use the view matrix to move around the scene (we moved backwards a little). OpenGL by itself is not familiar with the concept of a camera, but we can try to s
learnopengl.com
목표
- 사용자 입력에 따른 Walk around 카메라 정의
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);
카메라의 정보가 공유되어야 하므로, 전역 변수로 선언해준다. 여기서 cameraFront 변수는 카메라가 바라보는 지점이 아니라 카메라가 향할 방향 벡터를 의미한다.
glm::lookAt 함수를 사용하여 뷰 행렬을 생성한다.
glm::mat4 view;
view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);
이때, 카메라가 바라보는 타켓이 cameraPos + cameraFront 인 것을 확인할 수 있다. 이는 카메라를 움직이더라도 물체가 향한 방향을 바라보기 위함이다.
키보드의 W, A, S, D 입력에 따라 카메라의 위치에 해당하는 변수인 cameraPos의 값을 변화시킨다.
void processInput(GLFWwindow* window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
std::cout << "Pressed ESC" << std::endl;
glfwSetWindowShouldClose(window, true);
}
const float cameraSpeed = 0.01f;
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;
}
입력 이벤트를 처리하기 위한 콜백 함수인 processInput에 위와 같은 코드를 정의한다. glfwGetKey 함수는 입력된 키의 마지막 상태를 지정된 window에 반환하고, GLFW_PRESS는 눌렀을 때 반환되는 값이다. 따라서 지정된 키를 누르면 조건을 만족하여 동작을 실행하게 된다.
W, S 키를 누를 경우, 카메라가 향하는 방향 벡터 (0, 0, -1)에 지정된 카메라의 속도인 cameraSpeed를 곱하여 카메라의 위치를 조정한다. 해당 구현을 통해 카메라를 앞, 뒤로 움직이는 동작을 수행할 수 있다.
A, D 키를 누를 경우에는 카메라가 양 옆으로 이동해야 하는데, 외적을 이용하면 쉽게 구현이 가능하다. 카메라가 바라보는 방향벡터와 카메라의 위쪽에 해당하는 벡터가 수직이라는 점을 이용하면 외적을 수행하는 glm::cross 함수를 통해 계산이 가능하다. 일관된 카메라의 이동 속도를 위해, glm::normalize 함수를 통해 정규화한다.
이제 실행시키면 키보드 입력(W, A, S, D)에 따라 카메라의 위치를 조정할 수 있다.

'컴퓨터그래픽스' 카테고리의 다른 글
[OpenGL 공부] Camera (3) (0) | 2024.07.19 |
---|---|
[OpenGL 공부] Camera (1) (0) | 2024.02.02 |
[OpenGL 공부] Coordinates Systems (2) | 2024.02.01 |
[OpenGL 공부] Transformations (0) | 2024.01.20 |
[OpenGL 공부] Textures (exercises) (0) | 2024.01.16 |