【问题标题】:rotating object relative to camera in OpenGL在OpenGL中相对于相机旋转对象
【发布时间】:2011-12-16 02:53:23
【问题描述】:

我在 OpenGL 中遇到问题,让我的对象(行星)相对于当前相机旋转进行旋转。一开始它似乎可以工作,但是在旋转一点之后,旋转不再正确/相对于相机。

我正在计算屏幕上 mouseX 和 mouseY 移动的增量(差异)。旋转存储在名为“planetRotation”的 Vector3D 中。

这是我计算相对于 planetRotation 的旋转的代码:

Vector3D rotateAmount;
rotateAmount.x = deltaY;
rotateAmount.y = deltaX;
rotateAmount.z = 0.0;

glPushMatrix();
    glLoadIdentity();
    glRotatef(-planetRotation.z, 0.0, 0.0, 1.0);
    glRotatef(-planetRotation.y, 0.0, 1.0, 0.0);
    glRotatef(-planetRotation.x, 1.0, 0.0, 0.0);
    GLfloat rotMatrix[16];
    glGetFloatv(GL_MODELVIEW_MATRIX, rotMatrix);
glPopMatrix();

Vector3D transformedRot = vectorMultiplyWithMatrix(rotateAmount, rotMatrix);
planetRotation = vectorAdd(planetRotation, transformedRot);

理论上 - 这样做是在 'rotateAmount' 变量中设置旋转。然后通过将此向量与逆模型变换矩阵 (rotMatrix) 相乘,将其放入模型空间。

然后将这个变换后的旋转添加到当前旋转中。

要渲染这是正在设置的变换:

glPushMatrix();
    glRotatef(planetRotation.x, 1.0, 0.0, 0.0);
    glRotatef(planetRotation.y, 0.0, 1.0, 0.0);
    glRotatef(planetRotation.z, 0.0, 0.0, 1.0);
    //render stuff here
glPopMatrix();

相机有点晃动,我尝试执行的旋转似乎与当前变换无关。

我做错了什么?

【问题讨论】:

    标签: opengl camera transform rotational-matrices


    【解决方案1】:

    GAH! 不要那样做:

    glPushMatrix();
        glLoadIdentity();
        glRotatef(-planetRotation.z, 0.0, 0.0, 1.0);
        glRotatef(-planetRotation.y, 0.0, 1.0, 0.0);
        glRotatef(-planetRotation.x, 1.0, 0.0, 0.0);
        GLfloat rotMatrix[16];
        glGetFloatv(GL_MODELVIEW_MATRIX, rotMatrix);
    glPopMatrix();
    

    OpenGL 不是数学库。有适合这种工作的线性代数库。


    至于你的问题。 向量不适合存储旋转。您至少需要一个向量(旋转轴)和角度本身,或者更好的是四元数。

    也不添加旋转。它们不是可交换的,但是加法是可交换的操作。轮换实际上相乘

    如何修复您的代码:使用适当的数学方法从头开始重写。为此,请阅读“旋转矩阵”和“四元数”的主题(维基百科有它们)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多