標籤:
如上。
步驟:首先,變換模型視角;然後,改變顏色;最後,利用頂點數組繪製立方體。
原始碼如下:
#include <GL/glut.h> // 繪製立方體// 將立方體的八個頂點儲存到一個數組裡面static const float vertex_list[][3] = { -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f,};// 將要使用的頂點的序號儲存到一個數組裡面 static const GLint index_list[][2] = { {0, 1}, {2, 3}, {4, 5}, {6, 7}, {0, 2}, {1, 3}, {4, 6}, {5, 7}, {0, 4}, {1, 5}, {7, 3}, {2, 6}}; // 繪製立方體void DrawCube(void){ int i,j; glBegin(GL_LINES); for(i=0; i<12; ++i) // 12 條線段 { for(j=0; j<2; ++j) // 每條線段 2個頂點 { glVertex3fv(vertex_list[index_list[i][j]]); } } glEnd();}static float rotate = 0;static int times = 0;void renderScene(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // 清理顏色緩衝和深度緩衝 glMatrixMode(GL_MODELVIEW); // 對模型視景的操作 glLoadIdentity(); // 重設當前指定的矩陣為單位矩陣 glPushMatrix(); // 壓棧 //glTranslatef(-0.2, 0, 0); // 平移 //glScalef(1, 1, 1); // 縮放 times++; if(times > 100) { times = 0; } if(times % 100 == 0) // [0, 100) { rotate += 0.5; // [0, 20) } glRotatef(rotate, 0, 1, 0); // 旋轉 glRotatef(rotate, 1, 0, 0); // 動態顏色變換--紅->綠->藍->紅 if(rotate == 0) glColor3f(1, 0, 0); if(rotate ==90) glColor3f(0, 1, 0); if(rotate ==180) glColor3f(0, 0, 1); if(rotate ==270) glColor3f(1, 1, 0); if(rotate ==360) rotate = 0; DrawCube(); // 繪製立方體 glPopMatrix();// 出棧 glutSwapBuffers();} int main(int argc, char* argv[]){ glutInit(&argc, argv); // 初始化GLUT glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutInitWindowPosition(100, 100); // 顯示視窗在螢幕的相對位置 glutInitWindowSize(500, 500); // 設定顯示視窗大小 glutCreateWindow(argv[0]); // 建立視窗,附帶標題 glutDisplayFunc(renderScene); // 註冊顯示用的函數 glutIdleFunc(renderScene); // 註冊空閑用的函數 glutMainLoop(); // GLUT 狀態機器 return 0; }
openGL+VS2010的常式--旋轉變色立方體(三維)