本段代码展示了如何利用OpenGL库在C++中实现一个旋转的三维正方体,通过变换矩阵和渲染循环为用户提供动态的图形体验。
```c++
#include
#define GLUT_DISABLE_ATEXIT_HACK
#include
float AngleX = 45.0f;
float AngleY = 315.0f;
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Push the current matrix, rotate and draw a colored cube.
glPushMatrix();
glRotatef(AngleX, 1.0, 0.0, 0.0);
glRotatef(AngleY, 0.0, 1.0, 0.0);
glBegin(GL_QUADS);
// Front Face
glColor3ub(255, 96, 97);
glVertex3f(-1.0, -1.0, 1.0);
glVertex3f( 1.0, -1.0, 1.0);
glVertex3f( 1.0, 1.0, 1.0);
glColor3ub(254, 86, 7);
glVertex3f(-1.0, 1.0, 1.0);
// Back Face
glColor3ub(94, 198, 255);
glVertex3f(-1.0, -1.0, -1.0);
glVertex3f(-1.0, 1.0, -1.0);
glColor3ub(76, 247, 98);
glVertex3f( 1.0, 1.0, -1.0);
glVertex3f( 1.0, -1.0, -1.0);
// Top Face
glColor3ub(255, 76, 98);
glVertex3f(-1.0, 1.0, -1.0);
glColor3ub(247, 98, 252);
glVertex3f(-1.0, 1.0, 1.0);
glVertex3f( 1.0, 1.0, 1.0);
glColor3ub(66, 247, 98);
glVertex3f( 1.0, 1.0, -1.0);
// Bottom Face
glColor3ub(255, 247, 7);
glVertex3f(-1.0, -1.0, -1.0);
glVertex3f( 1.0, -1.0, -1.0);
glColor3ub(98, 66 , 252 );
glVertex3f( 1.0, -1.0, 1.0);
glColor3ub(74, 255 , 98);
glVertex3f(-1.0, -1.0, 1.0);
glEnd();
glPopMatrix();
glutSwapBuffers(); // Swap buffers
}
void reshape(int w, int h) {
if (h == 0)
h = 1;
GLfloat aspect = (GLfloat)w / (GLfloat)h;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(w <= h){
gluOrtho2D(-35.0f * aspect, 35.0f * aspect,-17.5f , -17.5f);
} else {
gluOrtho2D(-35.0f ,-35.0f /aspect, 35.f);
}
}
void keyboard(int key, int x, int y) { // Arrow keys for rotation
switch (key){
case GLUT_KEY_UP:
AngleX -= 5;
break;
case GLUT_KEY_DOWN:
AngleX += 5;
break;
case GLUT_KEY_LEFT :
AngleY -= 5;
break;
case GLUT_KEY_RIGHT :
AngleY += 5;
break;
}
if (AngleX > 360.0f) {
AngleX = 0.0f;
}
else if(AngleX < -360){
AngleX=360.f;
}
if (AngleY > 359.99 )
AngleY = 1;
else if(AngleY<-.01)
Angle