在OpenGL中相对于相机旋转对象

时间:2011-12-15 11:38:11

标签: opengl camera transform rotational-matrices

我在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();

相机摆动,我正在尝试执行的旋转,似乎与当前的变换无关。

我做错了什么?

1 个答案:

答案 0 :(得分:5)

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不是数学库。这种工作有适当的线性代数库。


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

也不会添加旋转。它们不是可交换的,但是增加是一种可交换的操作。事实上,轮换乘以

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