您应该跟踪相机方向以在正确的坐标系中移动相机,即相机本地(模型空间)。此外,为了避免万向节锁定,您应该开始使用四元数。使用四元数的原因是当你处理欧拉角时,遵循正确的旋转顺序很重要,否则你不会得到你想要的。
这是使用 glm 库的基于四元数的第一人称相机类的简单示例:
class Camera
{
public:
void move(glm::vec3 directions, glm::vec2 rotations, float frametime);
// ... constructors etc.
private:
glm::mat4 view_;
glm::vec3 camera_pos_;
glm::quat camera_orientation_;
const float camera_speed_;
}
// move directions - (forward/backward/0, left/right/0, up/down/0). each direction could be 1, -1 or 0
// rotations - (horizontal_amount, vertical_amount)
void Camera::move(glm::vec3 directions, glm::vec2 rotations, float frametime)
{
auto pitch = glm::quat(glm::vec3(-rotations.y, 0, 0.f));
auto yaw = glm::quat(glm::vec3(0, -rotations.x, 0.f));
camera_orientation_ = glm::normalize(yaw * camera_orientation_ * pitch);
auto camera_roll_direction = camera_orientation_ * glm::vec3(0, 0, -1);
auto camera_pitch_direction = camera_orientation_ * glm::vec3(-1, 0, 0);
// forward/backward move - all axes could be affected
camera_pos_ += directions[0] * camera_roll_direction * frametime * camera_speed_;
// left and right strafe - only xz could be affected
camera_pos_ += directions[1] * camera_pitch_direction * frametime * camera_speed_;
// up and down flying - only y-axis could be affected
camera_pos_.y += directions[2] * frametime * camera_speed_;
view_ = glm::lookAt(camera_pos_, camera_pos_ + camera_roll_direction,
glm::cross(camera_roll_direction, camera_pitch_direction));
}
并像这样使用它:
main_loop()
{
//...
glm::vec2 rotation;
glm::vec3 directions;
rotation.x = get_mouse_move_x_offset();
rotation.y = get_mouse_move_y_offset();
if(is_key_pressed(KEY_D)) directions.y = -1;
if(is_key_pressed(KEY_A)) directions.y = 1;
if(is_key_pressed(KEY_W)) directions.x = 1;
if(is_key_pressed(KEY_S)) directions.x = -1;
if(is_key_pressed(KEY_E)) directions.z = 1;
if(is_key_pressed(KEY_Q)) directions.z = -1;
cam.move(directions, rotation, frametime);
}
乘法的顺序yaw * camera_orientation_ * pitch
很重要,因为我们需要在世界空间中应用偏航变换,在模型空间中应用俯仰变换。
有关四元数和旋转的更多信息,请考虑阅读本教程。