1

现在,我让我的相机可以向前和向后移动。

我的箭头键有一个例程,可以更改 gluLookAt 调用中使用的相机变量的值。

gluLookAt(camera.ex,camera.ey, camera.ez,
    camera.cx,camera.cy,camera.cz,
    camera.x,camera.y,camera.z);


// Callback routine for non-ASCII key entry.
void specialKeyInput(int key, int x, int y)
{

if (key == GLUT_KEY_UP) camera.ez -= 0.1;
if (key == GLUT_KEY_DOWN) camera.ez += 0.1;
if (key == GLUT_KEY_LEFT) camera.cx -= 0.1;
if (key == GLUT_KEY_RIGHT) camera.cx += 0.1;

glutPostRedisplay();
}

我这样做所面临的问题是,即使我面对(比如说向左),并且我按下向上键,我正在偏移我的 camera.ez 值而不是正确的 camera.ex 值. 所以我的问题是,你如何在 OpenGL 中处理相机运动?我是否必须跟踪我正在查看的“角度”,并进行一些触发?

4

1 回答 1

3

您应该跟踪相机方向以在正确的坐标系中移动相机,即相机本地(模型空间)。此外,为了避免万向节锁定,您应该开始使用四元数。使用四元数的原因是当你处理欧拉角时,遵循正确的旋转顺序很重要,否则你不会得到你想要的。

这是使用 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很重要,因为我们需要在世界空间中应用偏航变换,在模型空间中应用俯仰变换。

有关四元数和旋转的更多信息,请考虑阅读教程。

于 2013-11-02T05:08:19.600 回答