3D Graphics Rendering Gaming Project in C++
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
#include <GL/glut.h> // GLUT library for handling OpenGL utilities // Variables for rotation float angleX = 0.0f; float angleY = 0.0f; // Function to initialize OpenGL settings void initGL() { glEnable(GL_DEPTH_TEST); // Enable depth testing for accurate rendering glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background color to black } // Function to display the scene void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear the screen and depth buffer glLoadIdentity(); // Reset the model-view matrix // Move the camera back along the z-axis glTranslatef(0.0f, 0.0f, -5.0f); // Rotate the cube glRotatef(angleX, 1.0f, 0.0f, 0.0f); // Rotate around the x-axis glRotatef(angleY, 0.0f, 1.0f, 0.0f); // Rotate around the y-axis // Draw a cube glutWireCube(2.0); // Draw a wireframe cube with a size of 2 units glutSwapBuffers(); // Swap the front and back buffers to display the rendered image } // Function to update rotation angles void update(int value) { angleX += 2.0f; // Increment the x-axis rotation angle angleY += 2.0f; // Increment the y-axis rotation angle if (angleX > 360) angleX -= 360; // Keep angleX within 0-360 degrees if (angleY > 360) angleY -= 360; // Keep angleY within 0-360 degrees glutPostRedisplay(); // Request to redraw the scene glutTimerFunc(16, update, 0); // Set up the timer to call update every 16 milliseconds (~60 FPS) } // Main function int main(int argc, char** argv) { glutInit(&argc, argv); // Initialize GLUT glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); // Set up display mode glutInitWindowSize(800, 600); // Set the window size glutCreateWindow("3D Rotating Cube"); // Create the window with a title initGL(); // Initialize OpenGL settings glutDisplayFunc(display); // Register the display function glutTimerFunc(25, update, 0); // Set up the timer for updating the scene glutMainLoop(); // Enter the GLUT main loop return 0; } |
Explanation: Include Libraries: #include <GL/glut.h>: This includes the GLUT (OpenGL Utility Toolkit) library, which provides functions to create and manage windows and handle events for OpenGL applications. Global Variables: float angleX and float angleY: These variables control the rotation angles of the cube along the x and y axes. Initialization Function (initGL): glEnable(GL_DEPTH_TEST): …
