如何在 opengl 中仅旋转特定对象而不影响其他对象?

How to rotate only a specific object without affecting the others in opengl?

本文关键字:对象 影响 其他 opengl 旋转      更新时间:2023-10-16

我在 OpenGL 中制作一个风扇,里面有杆子和旋转的东西,当我尝试旋转它们时,所有的风扇都随着杆子旋转,我应该如何修复它,我使用了glutPostRedisplay(),当我使用推送和 pup 矩阵旋转时,它根本不旋转, 它只以我写的角度旋转一次,有什么建议有帮助吗?

我在旋转中使用推送和 pup 矩阵,它根本不旋转,它只旋转一次

如果您使用glPushMatrix/glPopMatrix,则当前矩阵通过glPushMatrix存储在矩阵堆栈上,并在调用glPopMatrix时恢复。两者之间应用的所有矩阵变换都将丢失。

要实现连续旋转,您必须使用增加的旋转角度。创建一个全局变量angle并递增它。例如:

float angle = 0.0f;
void draw()
{
// ...
glPushMatrix();
// apply rotation and increase angle
glRotatef(angle, 1.0f, 0.0f, 0.0f);
angle += 1.0f;
// draw the object
// ...
glPopMatrix();
// ...
}

在老式的 opengl 中,您将封装一对 glPushMatrix(矩阵堆栈的存储状态(和 glPopMatrix(恢复以前的转换(调用之间的转换更改。

glPushMatrix();
glRotatef(45.0f, 0, 1, 0); //< or whatever your rotation is. 
drawObjectToBeRotated();
glPopMatrix();
// now any objects drawn here will not be affected by the rotation. 

在现代 OpenGL 中,对于正在绘制的每个网格,您需要上传一个单独的 ModelViewProjection 矩阵作为顶点着色器统一(有几种方法可以做到这一点,要么在统一变量、统一缓冲区对象、着色器存储缓冲区或某些实例化缓冲区输入中(。