Write a complete OpenGL program to demonstrate animation effects on a simple object.
Answer:-
simple OpenGL program that demonstrates basic animation effects using a rotating square
#include <GL/glut.h> // Include the GLUT header for OpenGL utilities // Rotation angle float angle = 0.0; // Function to display the scene void display() { // Clear the color buffer glClear(GL_COLOR_BUFFER_BIT); // Load the identity matrix glLoadIdentity(); // Move the object to the center of the window glTranslatef(0.0, 0.0, -5.0); // Rotate the object glRotatef(angle, 0.0, 1.0, 0.0); // Draw a simple square (a 2D object) in the center glBegin(GL_QUADS); glColor3f(1.0, 0.0, 0.0); // Red color glVertex2f(-1.0, 1.0); glVertex2f(1.0, 1.0); glVertex2f(1.0, -1.0); glVertex2f(-1.0, -1.0); glEnd(); // Swap the front and back buffers glutSwapBuffers(); } // Function to update the animation void update(int value) { angle += 2.0; // Increment the angle if (angle > 360) { angle -= 360; // Keep the angle within 0-360 degrees } glutPostRedisplay(); // Request a redraw glutTimerFunc(16, update, 0); // Call update() again after 16 milliseconds (60 FPS) } // Function to initialize OpenGL settings void init() { glClearColor(0.0, 0.0, 0.0, 1.0); // Set the background color to black glMatrixMode(GL_PROJECTION); // Set the projection matrix mode gluOrtho2D(-2.0, 2.0, -2.0, 2.0); // Set the orthographic projection } // Main function int main(int argc, char **argv) { glutInit(&argc, argv); // Initialize GLUT glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); // Set display mode glutInitWindowSize(500, 500); // Set window size glutCreateWindow("Simple Animation"); // Create window with title init(); // Initialize OpenGL settings glutDisplayFunc(display); // Register display function glutTimerFunc(25, update, 0); // Set up the timer function for animation glutMainLoop(); // Enter the GLUT event processing loop return 0; }
Explanation
- Initialization:
glutInit()
: Initializes GLUT.glutInitDisplayMode()
: Sets the display mode to double buffering and RGB color.glutInitWindowSize()
: Sets the size of the window.glutCreateWindow()
: Creates a window with the specified title.init()
: Sets up the background color and projection.
- Display Function (
display
):- Clears the screen.
- Translates and rotates the object.
- Draws a red square.
- Swaps buffers to update the display.
- Update Function (
update
):- Updates the rotation angle.
- Requests a redraw.
- Sets up a timer to call itself again after 16 milliseconds (for 60 FPS).
- Main Loop:
- Registers the display and timer functions.
- Enters the GLUT event processing loop.
This code will create a window displaying a rotating red square, demonstrating basic animation effects using OpenGL.