Original post address: http://ogldev.atspace.co.uk/www/tutorial14/tutorial14.html
In the previous tutorial, we placed the camera in a fixed position in the 3D space. In this chapter, we tried to control the camera and move it in any direction in the 3D space. We use a keyboard to control the camera's position and a mouse to change the camera's lookat direction, which is similar to camera control in the first-person shooting game. This chapter describes how to use the keyboard to control the camera position. The next chapter describes how to change the camera orientation with the mouse.
Note: When we move the camera with a keyboard, we only change the camera position without changing the lookat and up directions. The callback function for controlling the keyboard in glut is gluspecialfunc (). When a special key is pressed, this function will be executed, such as the direction key and page flip key. For normal buttons, you need to call back the Function Map ().
Main Code:
Create a new camera class to encapsulate all operations on the camera. This class saves the camera parameters and changes these parameters based on the received events to control the motion of the camera.
Camera. h
class Camera
{
public:
Camera();
Camera(const Vector3f& Pos, const Vector3f& Target, const Vector3f& Up);
bool OnKeyboard(int Key);
const Vector3f& GetPos() const
const Vector3f& GetTarget() const
const Vector3f& GetUp() const
private:
Vector3f m_pos;
Vector3f m_target;
Vector3f m_up;
};
The camera class stores three attributes: Position, lookat vector and up vector. The onkeyboard function is used to process Keyboard Events. If it is a specified key, the camera is controlled to move.
Camera. cpp
bool Camera::OnKeyboard(int Key)
{
bool Ret = false;
switch (Key) {
case GLUT_KEY_UP:
{
m_pos += (m_target * StepSize);
Ret = true;
}
break;
case GLUT_KEY_DOWN:
{
m_pos -= (m_target * StepSize);
Ret = true;
}
break;
case GLUT_KEY_LEFT:
{
Vector3f Left = m_target.Cross(m_up);
Left.Normalize();
Left *= StepSize;
m_pos += Left;
Ret = true;
}
break;
case GLUT_KEY_RIGHT:
{
Vector3f Right = m_up.Cross(m_target);
Right.Normalize();
Right *= StepSize;
m_pos += Right;
Ret = true;
}
break;
}
return Ret;
}
When you press the up and down arrow keys, the camera will move in the lookat direction, and the left and right arrow keys will move the 4 image along a righ vector.
Tutorial14.cpp
static void SpecialKeyboardCB(int Key, int x, int y)
{
GameCamera.OnKeyboard(Key);
}
static void InitializeGlutCallbacks()
{
glutDisplayFunc(RenderSceneCB);
glutIdleFunc(RenderSceneCB);
glutSpecialFunc(SpecialKeyboardCB);
}
We will register a new callback function to process special buttons.
Tutorial14.cpp
p.SetCamera(GameCamera.GetPos(), GameCamera.GetTarget(), GameCamera.GetUp());
This command is used to initialize the camera position.
After running the program, the interface is as follows: