-->

GLUT Tutorial: 2D Animation

GLUT Tutorial: 2D Animation

    This is the second tutorial on GLUT. In this tutorial I am going to show you how to do a 2D animation in GLUT. There are various methods that can be used to animate an object in GLUT. Among them, I will use a simple method that uses a function glutTimerFunc that registers the timer callback function func to be triggered in at least supplied time. For example glutTimerFunc( 25, update, 0) registers a call back function that calls the function update in every 25 milliseconds. We declared a GL variable rAngle with initial value of 0.0f. After each trigger we increase the value of rAngle by some amount that enables the object to  rotate  gradually according to the amount of angle increased. glRotatef is used to rotate the object in GLUT. We supply the angle by which an object to be rotated and the axis of rotation as arguments to the function glRotate. In this way we can do a simple animation ( rotation) in GLUT. The source code for rotation is given below.

    #include<windows.h>
    #include <iostream>
    #include <stdlib.h>
    #include <GL/glut.h>
    float rAngle  = 0.0;
    using namespace std;
    void handleKeypress(unsigned char key, int x, int y) {
    	switch (key) {
    		case 27:
    			exit(0);
    	}
    }
    void initRendering() {
    	glEnable(GL_DEPTH_TEST);
    }
    void handleResize(int w, int h) {
    	glViewport(0, 0, w, h);
    	glMatrixMode(GL_PROJECTION);
    	glLoadIdentity();
    	gluPerspective(45.0,
    				   (double)w / (double)h,
    				   1.0,
    				   200.0);
    }
    void update(int value){
        rAngle += 1.0f;
        if(rAngle > 360){
            rAngle -= 360;
        }
        glutPostRedisplay(); // Inform GLUT that the display has changed
        glutTimerFunc(25,update,0);//Call update after each 25 millisecond
    }
    void drawScene() {
    	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    	glMatrixMode(GL_MODELVIEW);
    	glLoadIdentity();
    	glRotatef(-rAngle, 0.0f, 0.0f, -1.0f);
    	glBegin(GL_TRIANGLES); //Begin triangle coordinates
    	//Triangle
    	glVertex3f(-0.5f, 0.5f, -5.0f);
    	glVertex3f(-1.0f, 1.5f, -5.0f);
    	glVertex3f(-1.5f, 0.5f, -5.0f);
    	glEnd(); //End triangle coordinates
    	glutSwapBuffers(); //Send the 3D scene to the screen
    }
    int main(int argc, char** argv) {
    	glutInit(&argc, argv);
    	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    	glutInitWindowSize(400, 400);
    	glutCreateWindow("Simple Animation - programming-technique.blogspot.com");
    	initRendering();
    	glutDisplayFunc(drawScene);
    	glutKeyboardFunc(handleKeypress);
    	glutReshapeFunc(handleResize);
    	glutTimerFunc(25,update,0);
    	glutMainLoop();
    	return 0;
    }
    fardi zayden
    @مرسلة بواسطة
    كاتب ومحرر اخبار اعمل في موقع دراسات تقنية .

    إرسال تعليق