這一課會把第二課中的三角形繞Y軸逆時針旋轉(zhuǎn)45°,正方形繞X軸順時針旋轉(zhuǎn)45°
頭文件中添加兩個變量表示三角形和正方形旋轉(zhuǎn)的角度。
private: ????QOpenGLContext?*m_context; ????GLfloat rtri; //?用于三角形的角度 ????GLfloat rquad; //?用于正方形的角度
在構(gòu)造函數(shù)中賦值
Lesson3::Lesson3(QWindow?*parent)?: ????QWindow(parent) ??,?m_context(0) { ????setSurfaceType(QWindow::OpenGLSurface); ????rtri=45.0f; ??//?三角形的旋轉(zhuǎn)角度 ????rquad=-45.0f;?//?正方形的旋轉(zhuǎn)角度 }
接下來需要修改render函數(shù)
void?Lesson3::render() { ????glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); ????glViewport(0,0,(GLint)width(),(GLint)height());?//?重置當(dāng)前視口 ????glMatrixMode(GL_PROJECTION);????????????????????//?選擇投影矩陣 ????glLoadIdentity();???????????????????????????????//?重置投影矩陣為單位矩陣 ????//?glu庫函數(shù)Qt不支持,但是glu庫函數(shù)是對gl庫函數(shù)的封裝,方便使用。因此我們可以自己 ????//?寫一個類似gluPerspective的函數(shù)myPerspective,用于設(shè)置透視。 ????//gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f); ????myPerspective(45.0,(GLfloat)width()/(GLfloat)height(),0.1,100.0); ????glMatrixMode(GL_MODELVIEW);//?選擇模型視圖矩陣 ????glLoadIdentity();??????????//?重置模型視圖矩陣為單位矩陣 ????glTranslatef(-1.5f,0.0f,-6.0f);?//?左移1.5單位,并移入屏幕6.0 ????glRotatef(rtri,0.0f,1.0f,0.0f); //?繞Y軸旋轉(zhuǎn)三角形 ????glBegin(GL_TRIANGLES); //?繪制三角形 ????glColor3f(1.0f,0.0f,0.0f); //?設(shè)置當(dāng)前色為紅色 ????glVertex3f(?0.0f,?1.0f,?0.0f); //?上頂點 ????glColor3f(0.0f,1.0f,0.0f); //?設(shè)置當(dāng)前色為綠色 ????glVertex3f(-1.0f,-1.0f,?0.0f); //?左下 ????glColor3f(0.0f,0.0f,1.0f); //?設(shè)置當(dāng)前色為藍色 ????glVertex3f(?1.0f,-1.0f,?0.0f); //?右下 ????glEnd();????????????????????????//?三角形繪制結(jié)束 ????//?注意:這里用原來的glTranslatef(3.0f,0.0f,0.0f);?換成了下面這兩句 ????glLoadIdentity(); ????glTranslatef(1.5f,0.0f,-6.0f);??//?右移1.5單位,并移入屏幕6.0 ????glRotatef(rquad,1.0f,0.0f,0.0f);//?繞X軸旋轉(zhuǎn)四邊形 ????glColor3f(0.5f,0.5f,1.0f); ????//?一次性將當(dāng)前色設(shè)置為紫色 ????glBegin(GL_QUADS); //?繪制正方形 ????glVertex3f(-1.0f,?1.0f,?0.0f); //?左上 ????glVertex3f(?1.0f,?1.0f,?0.0f); //?右上 ????glVertex3f(?1.0f,-1.0f,?0.0f); //?左下 ????glVertex3f(-1.0f,-1.0f,?0.0f); //?右下 ????glEnd(); ????//?正方形繪制結(jié)束 }
運行效果
glRotatef函數(shù)的用法:
函數(shù)原型:
? ? ? void glRotated(GLdouble angle,GLdouble x,GLdouble y,GLdouble z)
? ? ? void glRotatef(GLfloat angle,GLfloat x,GLfloat y,GLdouble z)
函數(shù)說明:
? ? ?這兩個函數(shù)用來計算旋轉(zhuǎn)矩陣,該矩陣圍繞原點到點(x,y,z)的向量逆時針旋轉(zhuǎn)angle度。
關(guān)于逆時針與順時針,可用右手定則:
即手握住某個坐標軸,大拇指指向某軸的正方向,其余四個手指的彎曲方向即為繞某軸旋轉(zhuǎn)的逆時針方向;反之為順時針方向。