OpenGL绘制旋转风车
时间: 2023-06-14 22:05:24 浏览: 158
以下是OpenGL绘制旋转风车的示例代码:
```c++
#include <GL/glut.h>
#include <math.h>
// 定义旋转角度、风车半径和叶片长度
GLfloat angle = 0.0f;
GLfloat radius = 0.5f;
GLfloat bladeLength = 1.0f;
void init(void) {
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_FLAT);
}
void drawWindmill() {
// 绘制风车柱
glPushMatrix();
glColor3f(0.5f, 0.5f, 0.5f);
glTranslatef(0.0f, -0.5f, 0.0f);
glScalef(0.1f, 1.0f, 0.1f);
glutSolidCube(1.0f);
glPopMatrix();
// 绘制风车叶片
glColor3f(0.0f, 0.0f, 1.0f);
glPushMatrix();
glTranslatef(0.0f, bladeLength / 2.0f, 0.0f);
glRotatef(angle, 0.0f, 0.0f, 1.0f);
glTranslatef(0.0f, bladeLength / 2.0f, 0.0f);
glBegin(GL_TRIANGLES);
glVertex3f(0.0f, 0.0f, 0.0f);
glVertex3f(-bladeLength / 8.0f, bladeLength, 0.0f);
glVertex3f(bladeLength / 8.0f, bladeLength, 0.0f);
glEnd();
glPopMatrix();
}
void display(void) {
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glTranslatef(0.0f, 0.0f, -2.0f);
glRotatef(angle, 0.0f, 1.0f, 0.0f);
glTranslatef(radius, 0.0f, 0.0f);
drawWindmill();
glPopMatrix();
glutSwapBuffers();
}
void reshape(int w, int h) {
glViewport(0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0, (GLfloat) w/(GLfloat) h, 1.0, 20.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0, 0.0, -5.0);
}
void idle(void) {
angle += 0.5f;
if (angle > 360.0f) {
angle -= 360.0f;
}
glutPostRedisplay();
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow("Windmill");
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutIdleFunc(idle);
glutMainLoop();
return 0;
}
```
这段代码使用了OpenGL的基本绘图函数和变换函数来绘制旋转的风车。其中,绘制风车柱使用了`glutSolidCube()`函数,绘制风车叶片使用了`glBegin()`和`glEnd()`函数。在`display()`函数中,使用了`glPushMatrix()`和`glPopMatrix()`函数对变换进行了保存和恢复。在`idle()`函数中,使用了`glutPostRedisplay()`函数来触发画面更新。
阅读全文