c++ - 了解 OpenGL glPushMatrix 和 glPopMatrix
问题描述
我是 OpenGL 新手并试图渲染两个对象,但只有一个对象应该旋转。我从这里了解到,我只能在一个对象上使用glPushMatrix
和glPopMatrix
应用旋转,但我的不起作用。
这是我的代码:
void renderObjs() {
//glPushMatrix();
drawPyramid(0, 0.7, 0, 0.289, 0, 0.167, -0.289, 0, 0.167, 0, 0, -0.33); // a function to draw triangles
//glPopMatrix();
glPushMatrix();
glRotatef(0.3f, 1.f, 1.f, 1.f);
drawPyramid(0 - 0.5, 0.7 - 0.5, 0 - 0.5, 0.289 - 0.5, 0 - 0.5, 0.167 - 0.5, -0.289 - 0.5, 0 - 0.5, 0.167 - 0.5, 0 - 0.5, 0 - 0.5, -0.33 - 0.5);
glPopMatrix();
}
int main() {
// some initialization
...codes here...
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
renderObjs();
glfwSwapBuffers(window);
glfwPollEvents();
}
// other useful functions
...codes here...
}
但我的金字塔都没有旋转。为什么会这样?我是否以错误的方式使用glPushMatrix
and ?glPopMatrix
解决方案
矩阵变换操作,例如glRotatef
,指定一个矩阵并将当前矩阵乘以新矩阵。glPushMatrix
将当前矩阵推入矩阵堆栈。glPopMatrix
从矩阵堆栈中弹出一个矩阵,并通过弹出的矩阵设置当前矩阵。角度的单位glRotate
是度:
glPushMatrix();
glRotatef(30.0f, 1.f, 1.f, 1.f);
drawPyramid(0 - 0.5, 0.7 - 0.5, 0 - 0.5, 0.289 - 0.5, 0 - 0.5, 0.167 - 0.5, -0.289 - 0.5, 0 - 0.5, 0.167 - 0.5, 0 - 0.5, 0 - 0.5, -0.33 - 0.5);
glPopMatrix();
如果要连续旋转物体,则需要在每张图像中增加旋转角度:
float angle = 0.0f;
void renderObjs() {
//glPushMatrix();
drawPyramid(0, 0.7, 0, 0.289, 0, 0.167, -0.289, 0, 0.167, 0, 0, -0.33); // a function to draw triangles
//glPopMatrix();
glPushMatrix();
glRotatef(angle, 1.f, 1.f, 1.f);
angle += 0.1f
drawPyramid(0 - 0.5, 0.7 - 0.5, 0 - 0.5, 0.289 - 0.5, 0 - 0.5, 0.167 - 0.5, -0.289 - 0.5, 0 - 0.5, 0.167 - 0.5, 0 - 0.5, 0 - 0.5, -0.33 - 0.5);
glPopMatrix();
}
推荐阅读
- postgresql - 无法找到或构造 Param[shapeless.::[String,shapeless.::[io.circe.Json,shapeless.HNil]]]
- oracle - PL/SQL 语句被忽略
- excel - VBA Excel在多行中水平对齐图片
- typescript - 如何在 `UploadedFile | 上进行模式匹配 上传文件[]`
- javascript - 将访问令牌与 Reactjs 前端一起使用
- unreal-engine4 - 哪个 UE4 类最适合在多人游戏中存储用户数据
- c# - 使用 EF Core 和 Fluent API 的复合键中每个键的唯一性
- sql - 如何以正确的值将科学记数法转换为从 excel 到 sql server 的文本?
- ios - 如何使用关联类型解析协议中的泛型属性?
- kotlin - 是否可以在 Kotlin 中创建“扩展类”?