OpenGL绘图过程中,平移后再次旋转,旋转中心为什么变了?

1、问题现象:绘制完三维模型后,直接旋转模型,旋转中心在模型的中心上,可以自由进行各个角度的旋转。但是,模型平移一个距离后,再次旋转时,发现旋转中心不在模型的中心了,导致旋转非常别扭。

问题现象对应的绘图代码如下:

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();// Reset the coordinate system before modifying

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
SetLight();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();// Reset the coordinate system before modifying

glRotatef(m_dRotX, 1.0, 0.0, 0.0);
glRotatef(m_dRotY, 0.0, 1.0, 0.0);
glRotatef(m_dRotZ, 0.0, 0.0, 1.0);
glScalef(m_glfScale, m_glfScale, m_glfScale);
glTranslatef(-m_dMoveDisX, -m_dMoveDisY, -m_dMoveDisZ); 

glColor4f(27 / 255.0f, 91 / 255.0f, 123 / 255.0f, 0.2f);

glBegin(GL_POINTS);

....

glEnd();
glFlush();
SwapBuffers(wglGetCurrentDC());


2、原因分析:模型平移后,旋转还是以原点进行,而模型中心已经不在原点上,导致旋转异常。

3、解决方案:

首先,调整旋转和平移的顺序,将平移glTranslatef放到旋转glRotatef前面执行,因为平移时会将原点移动到对应的坐标位置上,再次执行旋转时,还是以模型中心进行旋转;

其次,在平移旋转之前使用glPushMatrix方法保存当前的状态,然后在绘图完成后,执行glPopMatrix还原之前的矩阵状态,保证连续旋转、平移过程中的连续性。

修改后的代码如下:

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();// Reset the coordinate system before modifying

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
SetLight();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();// Reset the coordinate system before modifying


glPushMatrix();
glTranslatef(-m_dMoveDisX, -m_dMoveDisY, -m_dMoveDisZ);
glRotatef(m_dRotX, 1.0, 0.0, 0.0);
glRotatef(m_dRotY, 0.0, 1.0, 0.0);
glRotatef(m_dRotZ, 0.0, 0.0, 1.0);
glScalef(m_glfScale, m_glfScale, m_glfScale);


glColor4f(27 / 255.0f, 91 / 255.0f, 123 / 255.0f, 0.2f);
glBegin(GL_POINTS);

......

glEnd();
glPopMatrix();
glFlush();
SwapBuffers(wglGetCurrentDC());

你可能感兴趣的:(OpenGL)