正方体每个面都不一样
时间: 2023-09-30 14:13:02 浏览: 84
要让正方体每个面的颜色都不一样,可以在绘制每个面前先设置不同的颜色。OpenGL 中可以使用 glBegin(GL_POLYGON) 和 glEnd() 来绘制多边形,例如正方体的每个面就是一个由四个顶点组成的矩形,可以使用 glBegin(GL_POLYGON) 和 glEnd() 来绘制。完整代码如下:
```
#include "stdafx.h"
#include <stdio.h>
#include <glut.h>
void init(void) {
glClearColor(0.0,0.0,0.0,0.0);
glShadeModel(GL_FLAT);
}
void myReshape(int w, int h) {
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-1.0,1.0,-1.0,1.0,1.5,20.0);
glMatrixMode(GL_MODELVIEW);
}
void display(void) {
glClear(GL_COLOR_BUFFER_BIT);
// 绘制紫色茶壶
glColor3f(1.0,0.0,1.0);
glLoadIdentity();
gluLookAt(5.0,4.0,5.0,0.0,0.0,0.0,0.0,1.0,0.0);
glScalef(2.0,2.0,2.0);
glutWireTeapot(1);
// 绘制彩色正方体
glLoadIdentity();
gluLookAt(5.0,4.0,5.0,2.0,2.0,0.0,0.0,1.0,0.0);
glScalef(2.5,2.5,2.5);
// 绘制前面(红色)
glBegin(GL_POLYGON);
glColor3f(1.0, 0.0, 0.0);
glVertex3f(-0.5, -0.5, 0.5);
glVertex3f(0.5, -0.5, 0.5);
glVertex3f(0.5, 0.5, 0.5);
glVertex3f(-0.5, 0.5, 0.5);
glEnd();
// 绘制后面(黄色)
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 0.0);
glVertex3f(-0.5, -0.5, -0.5);
glVertex3f(0.5, -0.5, -0.5);
glVertex3f(0.5, 0.5, -0.5);
glVertex3f(-0.5, 0.5, -0.5);
glEnd();
// 绘制左面(绿色)
glBegin(GL_POLYGON);
glColor3f(0.0, 1.0, 0.0);
glVertex3f(-0.5, -0.5, -0.5);
glVertex3f(-0.5, -0.5, 0.5);
glVertex3f(-0.5, 0.5, 0.5);
glVertex3f(-0.5, 0.5, -0.5);
glEnd();
// 绘制右面(蓝色)
glBegin(GL_POLYGON);
glColor3f(0.0, 0.0, 1.0);
glVertex3f(0.5, -0.5, -0.5);
glVertex3f(0.5, -0.5, 0.5);
glVertex3f(0.5, 0.5, 0.5);
glVertex3f(0.5, 0.5, -0.5);
glEnd();
// 绘制上面(白色)
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(-0.5, 0.5, -0.5);
glVertex3f(0.5, 0.5, -0.5);
glVertex3f(0.5, 0.5, 0.5);
glVertex3f(-0.5, 0.5, 0.5);
glEnd();
// 绘制下面(黑色)
glBegin(GL_POLYGON);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(-0.5, -0.5, -0.5);
glVertex3f(0.5, -0.5, -0.5);
glVertex3f(0.5, -0.5, 0.5);
glVertex3f(-0.5, -0.5, 0.5);
glEnd();
glFlush();
}
void main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
glutInitWindowSize(500,500);
glutInitWindowPosition(100,100);
glutCreateWindow("3D Cube");
init();
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glutMainLoop();
}
```
阅读全文