1. 程式人生 > >旋轉的“金字塔”

旋轉的“金字塔”

點選滑鼠左鍵加速,右鍵減速

#include <GL/glut.h>
#include <stdlib.h>
static float  rtri=0.0f,acc=0.1f;//金字塔旋轉角度
void init() 
{
       glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
       glShadeModel(GL_SMOOTH);//設為smooth處理方式,注意看區別
       glEnable(GL_DEPTH_TEST);//啟用深度測試
}
void display()
{
       glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);    //清除顏色快取和深度快取
       glLoadIdentity();
       glTranslatef(-1.5f,0.0f,-6.0f);//平移
       glRotatef((GLfloat)rtri,0.0f,1.0f,0.0f);//旋轉
       glBegin(GL_TRIANGLES);
       glColor3f(1.0f,0.0f,0.0f);
       glVertex3f( 0.0f, 1.0f, 0.0f);
       glColor3f(0.0f,1.0f,0.0f);
       glVertex3f(-1.0f,-1.0f, 1.0f);
       glColor3f(0.0f,0.0f,1.0f);
       glVertex3f( 1.0f,-1.0f, 1.0f);

       glColor3f(1.0f,0.0f,0.0f);
       glVertex3f( 0.0f, 1.0f, 0.0f);
       glColor3f(0.0f,0.0f,1.0f);
       glVertex3f( 1.0f,-1.0f, 1.0f);
       glColor3f(0.0f,1.0f,0.0f);
       glVertex3f( 1.0f,-1.0f, -1.0f);

       glColor3f(1.0f,0.0f,0.0f);
       glVertex3f( 0.0f, 1.0f, 0.0f);
       glColor3f(0.0f,1.0f,0.0f);
       glVertex3f( 1.0f,-1.0f, -1.0f);
       glColor3f(0.0f,0.0f,1.0f);
       glVertex3f(-1.0f,-1.0f, -1.0f);

       glColor3f(1.0f,0.0f,0.0f);
       glVertex3f( 0.0f, 1.0f, 0.0f);
       glColor3f(0.0f,0.0f,1.0f);
       glVertex3f(-1.0f,-1.0f,-1.0f);
       glColor3f(0.0f,1.0f,0.0f);
       glVertex3f(-1.0f,-1.0f, 1.0f);
       glEnd();
       glutSwapBuffers();//交換雙快取
}
 
void reshape (int width, int height)
{
       glViewport(0, 0, width, height); 
       glMatrixMode(GL_PROJECTION);
       glLoadIdentity();
       gluPerspective(45.0f, (GLfloat)width/(GLfloat)height, 0.1f, 100.0f);
       glMatrixMode(GL_MODELVIEW);
       glLoadIdentity();
}
 
void idle()
{
	rtri=rtri+acc;
	glutPostRedisplay();
}
void mouse(int button, int state, int x, int y)
{
	if (button == GLUT_LEFT_BUTTON)//如果滑鼠左鍵被按下或者被放開
	{
		if (state == GLUT_DOWN)//如果某個滑鼠鍵被按下
		{
			acc+=0.1f;
		}
		glutPostRedisplay(); 
	}
	else if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
	{					
			acc-=0.1f;
		glutPostRedisplay(); 
	}
	else
	{
		if(state==GLUT_DOWN)
			exit(0);
		glutPostRedisplay();
	}
}
int main(int argc, char** argv)
{
       glutInit(&argc, argv);
       glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);//使用雙快取模式和深度快取
       glutInitWindowSize(640, 480); 
       glutInitWindowPosition(100, 100);
       glutCreateWindow("Transform2");
       init();
       glutDisplayFunc(display);
	   glutIdleFunc(idle);//設定空閒時呼叫的函式
       glutReshapeFunc(reshape);
	   glutMouseFunc(mouse);
       glutMainLoop();
       return 0;
}

執行截圖: