use*_*465 0 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);
Run Code Online (Sandbox Code Playgroud)
理论上 - 它的作用是在'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();
Run Code Online (Sandbox Code Playgroud)
相机有点摆动,我试图执行的旋转,似乎与当前的变换无关.
我究竟做错了什么?
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();
Run Code Online (Sandbox Code Playgroud)
OpenGL不是数学库.这种工作有适当的线性代数库.
至于你的问题.矢量不适合存储旋转.您至少需要一个Vector(旋转轴)和角度本身,或者更好的是四元数.
旋转也不会增加.它们不是可交换的,但是增加是一种可交换的操作.旋转实际上是倍增的.
如何修复代码:使用适当的数学方法从头开始重写代码.为此,请阅读"旋转矩阵"和"四元数"(维基百科有它们)的主题.