OpenGL 旋转的四棱锥

四棱锥在屏幕中央,绕y轴旋转,可加速,减速。

建立四棱锥的模型用之前最简单粗暴的方式,四个三角形搭建。

旋转,平移,放缩直接调用已有函数。


重点:添加了对鼠标,键盘事件的处理,

glutKeyboardFunc(keyboard);
glutMouseFunc(mouse);  

其中的参数及意义详见:Glut处理鼠标事件    OpenGL键盘控制键值


使用说明:点击鼠标左键加速,右键减速,点中间滚轮退出

#include"stdafx.h"
#include 
#include 
#include
using namespace std;
float rtri = 30;//金字塔旋转角度
float speed = 0.1;
void init(void){
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	glShadeModel(GL_SMOOTH);//设为smooth处理方式,注意看区别
	glEnable(GL_DEPTH_TEST);//激活深度测试
}

void display(void){
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);    //清除颜色缓存和深度缓存
	glLoadIdentity();
	glTranslatef(0.0f, 0.0f, -6.0f);	//平移,向后移6,z轴垂直屏幕向外
	glRotatef(rtri, 0.0f, 1.0f, 0.0f);	//旋转,绕y轴
	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();

	rtri += speed;//加一个角度
	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 mouse(int button, int state, int x, int y){
	if (button == GLUT_LEFT_BUTTON)    //鼠标左右中间键控制速度退出
		speed = min(1.0, speed + 0.1);
	if (button == GLUT_RIGHT_BUTTON)
		speed = max(0.1, speed - 0.1);
	if (button == GLUT_MIDDLE_BUTTON)
		exit(0);
}
void keyboard(unsigned char key, int x, int y){
	switch (key){	//考虑添加键盘命令,交互式控制金字塔的旋转
	case '+':
		speed = min(1.0, speed + 0.1); break;
	case '-':
		speed = max(0.1, speed - 0.1); break;
	default:
		exit(0); break;
	}
}

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);
	glutReshapeFunc(reshape);
	glutKeyboardFunc(keyboard);
	glutMouseFunc(mouse);
	glutIdleFunc(display);//设置空闲时调用的函数
	glutMainLoop();
	return 0;
}
OpenGL 旋转的四棱锥_第1张图片

你可能感兴趣的:(OpenGL)