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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
|
#include <iostream>
#include <stdlib.h>
#include <glut.h>
using namespace std;
float _angle = 0.0f;//For rotating the car
float xpos = 0.0f;//For moving the car in the X axis
float ypos = 0.0f;//For moving the car in the Y axis
float cameraheight = -20.0f;//For zoom or unzoom the camera
//Called when a key is pressed
void handleKeypress(unsigned char key, int x, int y) {
switch (key) {
case 27: //ESC
exit(0);
break;
case 49: //Number 1
_angle += 1.0f;
break;
case 50: //Number 2
_angle -= 1.0f;
break;
case 51: //Number 3
cameraheight -= 5.0f;
break;
case 52: //Number 4
cameraheight += 5.0f;
break;
case 53: //Number 5
xpos += 1.0f;
break;
case 54: //Number 6
ypos += 1.0f;
break;
}
}
//Initializes 3D rendering
void initRendering() {
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL); //Enable color
glClearColor(0.2f, 0.2f, 0.2f, 1.0f); //Background color is sky blue
}
//Called when the window is resized
void handleResize(int w, int h) {
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, (double)w / (double)h, 0.01/*Min render distance*/, 1000.0/*Max distance*/);//Meters
}
//Draws the 3D scene
void drawScene() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, cameraheight);//I have moved the circuit and the car 20 meters under, so now
//the camera is "set" at 20 meters high than the car and the circuit
//CAR
glPushMatrix(); //Save the transformations performed thus far
glTranslatef(xpos*sinf(_angle), ypos*cosf(_angle), 0.0f);
glRotatef(_angle, 0.0f, 0.0f, 1.0f);
glBegin(GL_QUADS);
glColor3f(1.0f, 0.0f, 0.0f); //Red Ferrari
glVertex3f(-2.25f, 1.0f, 0.0f); //Meters (4,5m long per 2,25m wide)
glVertex3f(2.25f, 1.0f, 0.0f);
glVertex3f(2.25f, -1.0f, 0.0f);
glVertex3f(-2.25f, -1.0f, 0.0f);
glEnd();
glPopMatrix(); //Undo the move of the car
glutSwapBuffers();
}
void update(int value) {
if (_angle > 360) {
_angle -= 360;
}
glutPostRedisplay();
glutTimerFunc(16, update, 0);
}
int main(int argc, char** argv) {
//Initialize GLUT
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(320, 240);
//Create the window
glutCreateWindow("Test");
initRendering();
//Set handler functions
glutDisplayFunc(drawScene);
glutKeyboardFunc(handleKeypress);
glutReshapeFunc(handleResize);
glutTimerFunc(16, update, 0); //Add a timer
glutMainLoop();
return 0;
}
|