OpenGL实现动画旋转

2017-08-27  本文已影响0人  小_狐_狸

在xy平面上绕z轴连续旋转一个正六边形。

#include#include#include

const double TWO_PI = 6.2831853;

GLsizei winWidth = 500, winHeight = 500;

GLuint regHex;  //Define name for display list

static GLfloat rotTheta = 0.0;

class scrPt

{

public:

GLint

x, y;

};

static void init(void){

scrPt hexVertex;

GLdouble hexTheta;

GLint k;

glClearColor(1.0, 1.0, 1.0, 0.0);

/* set up a display list for a red regular hexagon */

/* Vertices for the hexagon are six equally spaced points around the circumference of a circle */  //六边形的顶点在圆周上是6个等距点

//glGenLists(GLuint range)是更安全的创建列表的函数 由于创建的显示列表组是连续的,glGenLists()首先检查有哪些值已经被占用,然后从最小的值开始建立连续的显示列表

regHex = glGenLists(1);

glNewList(regHex, GL_COMPILE);  //类似glBegin

glColor3f(1.0, 0.0, 0.0);

glBegin(GL_POLYGON);

for (k = 0; k < 6; k++){

hexTheta = TWO_PI*k / 6;

hexVertex.x = 150 + 100 * cos(hexTheta);

hexVertex.y = 150 + 100 * sin(hexTheta);

glVertex2i(hexVertex.x, hexVertex.y);

}

glEnd();

glEndList();

}

void displayHex(void){

glClear(GL_COLOR_BUFFER_BIT);

glPushMatrix();

glRotatef(rotTheta, 0.0, 0.0, 1.0);

glCallList(regHex);

glPopMatrix();

glutSwapBuffers();

glFlush();

}

/*用于激活旋转,在每次按下鼠标中键时将旋转角度增加3°*/

void rotateHex(void) {

rotTheta += 3.0;

if (rotTheta > 360.0){

rotTheta -= 360.0;

glutPostRedisplay();

}

}

void winReshapeFcn(GLint newWidth, GLint newHeight){

glViewport(0, 0, (GLsizei)newWidth, (GLsizei)newHeight);

glMatrixMode(GL_PROJECTION);

//glLoadIdentity()的作用就是把矩阵堆栈中的在栈顶的那个矩阵置为单位矩阵,好让之前的任何变换都不影响后面的变化。

glLoadIdentity();

gluOrtho2D(-320.0, 320.0, -320.0, 320.0);

glMatrixMode(GL_MODELVIEW);

glLoadIdentity();

glClear(GL_COLOR_BUFFER_BIT);

}

void mouseFcn(GLint button, GLint action, GLint x, GLint y){

switch (button)

{

case GLUT_MIDDLE_BUTTON:    //start the rotation

if (action == GLUT_DOWN)

glutIdleFunc(rotateHex);

break;

case GLUT_RIGHT_BUTTON:

if (action==GLUT_DOWN)

glutIdleFunc(NULL);

break;

default:

break;

}

}

int main(int argc, char**argv){

glutInit(&argc, argv);

glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);

glutInitWindowPosition(150, 150);

glutInitWindowSize(winWidth, winHeight);

glutCreateWindow("Aniomation Example");

init();

glutDisplayFunc(displayHex);

glutReshapeFunc(winReshapeFcn);

glutMouseFunc(mouseFcn);

glutMainLoop();

return 0;

}

上一篇下一篇

猜你喜欢

热点阅读