OpenGL翻译旋转比例转换

时间:2013-08-18 10:57:36

标签: opengl rotation translation transformation

我正在尝试创建用户firendly转换类(例如Unity),它只保存(或仅对用户可见)位置,旋转和平移向量。

通过使用glTranslate,glRotate和glScale函数,OpenGL很容易应用转换。我将在每个对象即将被绘制之前调用Transform方法。但我在改变与轮换相关的位置时遇到了麻烦。这是我的代码。

//对象的示例渲染方法

    void Render()
    {
        glPushMatrix();
        glMatrixMode(GL_MODELVIEW);

        transform->Transform();

        glEnable(GL_COLOR_MATERIAL);
        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_COLOR_ARRAY);

        glColorPointer(3, GL_FLOAT, 0, m_colors->constData());
        glVertexPointer(3, GL_FLOAT, 0, m_positions->constData());
        glDrawArrays(GL_LINES, 0, 6);

        glDisable(GL_COLOR_MATERIAL);
        glDisableClientState(GL_VERTEX_ARRAY);
        glDisableClientState(GL_COLOR_ARRAY);

        glPopMatrix();
    }

//转换类

    class Transformation
    {

    public:

        QVector3D Position;
        QVector3D Rotation;
        QVector3D Scale;

        Transformation()
        {
            Position = QVector3D(0.0f, 0.0f, 0.0f);
            Rotation = QVector3D(0.0f, 0.0f, 0.0f);
            Scale    = QVector3D(1.0f, 1.0f, 1.0f);
        }

        ~Transformation()
        {

        }

        void Translate(const QVector3D& amount)
        {

        }

        void Rotate(const QVector3D& amount)
        {
            Rotation += amount;

            Rotation.setX(AdjustDegree(Rotation.x()));
            Rotation.setY(AdjustDegree(Rotation.y()));
            Rotation.setZ(AdjustDegree(Rotation.z()));
        }

        void Transform()
        {
            // Rotation
            glRotatef(Rotation.x(), 1.0f, 0.0f, 0.0f);
            glRotatef(Rotation.y(), 0.0f, 1.0f, 0.0f);
            glRotatef(Rotation.z(), 0.0f, 0.0f, 1.0f);

            // Translation
            glTranslatef(Position.x(), Position.y(), Position.z());

            // Scale
            glScalef(Scale.x(), Scale.y(), Scale.z());
        }

    };

我该如何翻译?

1 个答案:

答案 0 :(得分:2)

openGL中的转换存储在堆栈中,然后它们反向应用于模型。在您的代码中,首先应用比例,然后是平移,最后是旋转。由于旋转是由(0,0,0)构成的,如果移动(平移)了对象,则会改变其位置。要旋转对象,其中心应为(0,0,0)。

正确的转换顺序是:缩放/旋转然后翻译

因此,在您的代码中,翻译应该是您进行的第一次转换。