0

我正在尝试上一门课程来在 OpenGL 中穿越世界,但我遇到了数学问题。我的想法是使用 glm 中的函数 lookAt 将观察者设置在我想要的位置,然后只使用我传递给函数的点进行操作。我认为我所做的旋转功能是正确的,但是 walk 方法中的平移部分似乎是错误的,当我尝试在世界中行走时,如果我只是平移或旋转,事情就正常了,但是当我做这两件事只是搞砸了。

这是到目前为止的课程:

#ifndef OBSERVER_H
#define OBSERVER_H

#include <GL/gl.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

class Observer {

private:

    glm::vec3 eye, center, upp;

public:

    glm::mat4 view;

    Observer() {}
    ~Observer() {}    

    void initialize(glm::vec3 eye, glm::vec3 center, glm::vec3 upp);
    void walk(GLfloat distance);
    void pitch(GLfloat pitch);
    void yaw(GLfloat yaw);
    void roll(GLfloat roll);
    void setView();
};

void Observer::initialize(glm::vec3 eye, glm::vec3 center, glm::vec3 upp) 
{
    this->eye = eye;
    this->center = center;
    this->upp = upp;
}

void Observer::walk(GLfloat distance) 
{
    glm::vec3 vector = glm::normalize(center - eye);
    glm::vec3 translate = vector*distance - vector;

    eye += translate;
    center += translate;
    upp += translate;
}

void Observer::roll(GLfloat roll) {
    glm::mat4 rotate(1.0f);

    rotate = glm::rotate(rotate, roll, glm::vec3(center - eye));

    center = glm::vec3(rotate * glm::vec4(center, 1.0f));
    upp = glm::vec3(rotate * glm::vec4(upp, 1.0f));
}

void Observer::yaw(GLfloat yaw) {
    glm::mat4 rotate(1.0f);

    rotate = glm::rotate(rotate, yaw, glm::vec3(upp - eye));

    center = glm::vec3(rotate * glm::vec4(center, 1.0f));
    upp = glm::vec3(rotate * glm::vec4(upp, 1.0f));
}

void Observer::pitch(GLfloat pitch) {
    glm::mat4 rotate(1.0f);
    glm::vec3 cross = glm::cross(center - eye, upp - eye);

    rotate = glm::rotate(rotate, pitch, cross);

    center = glm::vec3(rotate * glm::vec4(center, 1.0f));
    upp = glm::vec3(rotate * glm::vec4(upp, 1.0f));
}

void Observer::setView() 
{
    view = glm::lookAt(eye, center, upp);
}

#endif

所以在我开始绘制之前,我在程序的其他部分设置了这个类的视图矩阵。谁能告诉我我的数学是否正确?

4

1 回答 1

2

当您 时walk,您只想变换眼睛和中心位置,而不是upp矢量。只需删除该upp += translate;行。

于 2013-03-24T21:59:02.387 回答