shardy

OpenGL Jump & Collision

Apr 8th, 2013
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 8.02 KB | None | 0 0
  1. #include <GL/glut.h>                                                //Use glut or freeglut library
  2.  
  3. int  keyDown[256];                                                  //Array of key codes
  4. void keyPressed(unsigned char key, int x, int y){keyDown[key]=1;}   //If key pressed its down
  5. void keyUp     (unsigned char key, int x, int y){keyDown[key]=0;}   //Else key is up
  6.  
  7. const int WIN_X  = 640, WIN_Y = 480;                                //Window size
  8. const int FPS    = 60;                                              //Frames per second
  9. int   timeFrame  = 0;                                               //TimeFrame
  10. float delta      = 0.0f;                                            //Jump physics
  11. float x_Pos = 0, y_Pos = 0;                                         //Sprite coordinates
  12. float velocity   = 0.01f;                                           //Sprite velocity
  13. float gravity    = 0.0f;                                            //Gravity force
  14. float jumpHeight = 0.5f;                                            //Jump height limit
  15. float jumpLength = 5.0f;                                            //Length of natural jump
  16.  
  17. struct RECT{float x, y, w, h;};                                     //Construct Rectangle
  18. RECT sprite    = {  0,  0,  10, 10};                                //Attributes for Sprite
  19. RECT platform  = { 50, 20, 120, 10};                                //Attributes for Platform
  20. RECT platform2 = {150, 50,  50, 10};                                //Attributes for Platform2
  21. //RECT platform3 = { 50, 30, 100, 10};
  22. //RECT platform4 = { 50, 40,  80, 10};
  23. //RECT platform5 = { 50, 50,  60, 10};
  24.  
  25. void init(){                                                        //Initialise
  26.     glViewport(0.f, 0.f, WIN_X, WIN_Y );                            //Set the viewport
  27.     glEnable(GL_TEXTURE_2D);                                        //Enable textures for mapping
  28.     glMatrixMode( GL_PROJECTION );                                  //Initialise Projection Matrix
  29.     glLoadIdentity();                                               //Load current
  30.     gluOrtho2D(0.0, 200.0, 0.0, 150.0);                             //Set 2D Ortho view
  31.     glMatrixMode( GL_MODELVIEW );                                   //Initialise Modelview Matrix
  32.     glClearColor( 0.f, 0.f, 0.f, 1.f );                             //Initialise clear color
  33. }
  34.  
  35. bool check_collision( RECT sprite, RECT platform ){                 //Function to check collisions
  36.     float sprite_Left,   plat_Left;                                 //Left sides of the rectangles
  37.     float sprite_Right,  plat_Right;                                //Right sides of the rectangles
  38.     float sprite_Top,    plat_Top;                                  //Top sides of the rectangles
  39.     float sprite_Bottom, plat_Bottom;                               //Bottom sides of the rectangles
  40.     sprite_Left   = sprite.x;                                       //Calculate the left side of first object
  41.     sprite_Right  = sprite.x + sprite.w;                            //Calculate the right side of first object
  42.     sprite_Top    = sprite.y;                                       //Calculate the top side of first object
  43.     sprite_Bottom = sprite.y + sprite.h;                            //Calculate the bottom side of first object
  44.     plat_Left   = platform.x;                                       //Calculate the left side of second object
  45.     plat_Right  = platform.x + platform.w;                          //Calculate the right side of second object
  46.     plat_Top    = platform.y;                                       //Calculate the top side of second object
  47.     plat_Bottom = platform.y + platform.h;                          //Calculate the bottom side of second object
  48.     if(sprite_Bottom +y_Pos <= plat_Top    ){return false;}         //If sprites bottom is on or inside platforms top, colliding
  49.     if(sprite_Top    +y_Pos >= plat_Bottom ){return false;}         //If sprites top is on or inside platforms bottom, colliding
  50.     if(sprite_Right  +x_Pos <= plat_Left   ){return false;}         //If sprites right is on or inside platforms left, colliding
  51.     if(sprite_Left   +x_Pos >= plat_Right  ){return false;}         //If sprites left is on or inside platforms right, colliding
  52.     return true;                                                    //If no side(s) are touching, objects not colliding
  53. }
  54.  
  55. void move(){                                                        //Function to control moving sprite
  56.     if(check_collision(sprite,platform)                             //If colliding...
  57.         || check_collision(sprite,platform2)){
  58.         if(keyDown[115]){ y_Pos += (velocity*2);}                   //IF key is still down, return to previous velocity
  59.         if(keyDown[119]){ y_Pos -= (velocity*2);}                   //IF key is still up, return to previous velocity
  60.         if(keyDown[100]){ x_Pos -= (velocity*2);}                   //IF key is still right, return to previous velocity
  61.         if(keyDown[97] ){ x_Pos += (velocity*2);}                   //IF key is still left, return to previous velocity
  62.     }
  63.     glTranslatef(sprite.x+x_Pos, sprite.y+y_Pos, 0.0);              //Move sprite to calculated coordinates in x/y position
  64. }
  65.  
  66. void drawSprite (RECT rect){                                        //Function to draw sprite
  67.     glPushMatrix();                                                 //Push matrix
  68.     move();                                                         //Check collision and move appropriately
  69.     glBegin(GL_QUADS);                                              //Begin drawing rectangle
  70.         glColor3f(0.0f, 0.0f, 1.0f);                                //Set colour(s) of rectangle
  71.         glVertex3f(rect.x, rect.y, 0.0);                            //First point of quadrilateral or polygon
  72.         glVertex3f(rect.x, rect.y+rect.h, 0.0);                     //Second point of quadrilateral or polygon
  73.         glVertex3f(rect.x+rect.w, rect.y+rect.h, 0.0);              //Third point of quadrilateral or polygon
  74.         glVertex3f(rect.x+rect.w, rect.y, 0.0);                     //Final point of quadrilateral or polygon
  75.     glEnd();                                                        //Finish drawing rectangle
  76.     glPopMatrix();                                                  //Pop current matrix
  77. }
  78.  
  79. void drawPlatform (RECT rect){                                      //Function to draw platform
  80.     glBegin(GL_QUADS);                                              //Begin drawing rectangle
  81.         glColor3f(1.0f,0.0f,0.0f);                                  //Set colour(s) of rectangle
  82.         glVertex3f(rect.x, rect.y, 0.0);                            //First point of quadrilateral or polygon
  83.         glVertex3f(rect.x, rect.y+rect.h, 0.0);                     //Second point of quadrilateral or polygon
  84.         glVertex3f(rect.x+rect.w, rect.y+rect.h, 0.0);              //Third point of quadrilateral or polygon
  85.         glVertex3f(rect.x+rect.w, rect.y, 0.0);                     //Final point of quadrilateral or polygon
  86.     glEnd();                                                        //Finish drawing rectangle
  87. }
  88.  
  89. void controls(void){
  90.     if(!timeFrame){timeFrame = glutGet(GLUT_ELAPSED_TIME);}         //Assign elapsed time
  91.     int now = glutGet(GLUT_ELAPSED_TIME);                           //Current time
  92.     int elapsedMilliseconds = now - timeFrame;                      //Calculate milliseconds
  93.     float delta = elapsedMilliseconds/1000.0f;                      //Calculate delta
  94.     timeFrame = now;                                                //Assign time frame
  95.  
  96.     if(keyDown[119]){                                               //While 'w' key is pressed and not colliding
  97.         if(!check_collision(sprite,platform)                        //If not colliding...
  98.             && !check_collision(sprite,platform2)){
  99.             y_Pos += jumpHeight;                                    //Jump up
  100.             if(keyDown[97] ){x_Pos -= velocity*jumpLength;}         //While 'w' and 'a' are pressed, simulate arc of jump/gravity
  101.             if(keyDown[100]){x_Pos += velocity*jumpLength;}         //While 'w' and 'd' are pressed, simulate arc of jump/gravity
  102.         }
  103.         else                                                        //Else you must be colliding, bounce off
  104.             y_Pos -= jumpHeight;
  105.     }
  106.     if(keyDown[115]){y_Pos -= velocity;}                            //While 's' key is pressed
  107.     if(keyDown[97] ){x_Pos -= velocity;}                            //While 'a' key is pressed
  108.     if(keyDown[100]){x_Pos += velocity;}                            //While 'd' key is pressed
  109.    
  110.     //gravity
  111.     if(y_Pos>0){                                                    //If above ground
  112.         if(!check_collision(sprite,platform)                        //And not colliding
  113.             && !check_collision(sprite,platform2)){
  114.             gravity-=5*delta;                                       //Calculate gravity force
  115.             y_Pos+=gravity;                                         //Descend to ground
  116.         }
  117.         if(keyDown[97] ){x_Pos -= velocity*2;}                      //While off ground, whilst 'a' is pressed, move left
  118.         if(keyDown[100]){x_Pos += velocity*2;}                      //While off ground, whilst 'd' is pressed, move right
  119.     }
  120.     else{gravity=0;}                                                //Else, on ground, so gravity force is zero
  121. }
  122.  
  123. void display(void){                                                 //Render and display
  124.     glClear(GL_COLOR_BUFFER_BIT);                                   //Clear buffer
  125.         controls();                                                 //User input to control sprite
  126.         drawSprite(sprite);                                         //Render sprite
  127.         drawPlatform(platform);                                     //Render platform
  128.         drawPlatform(platform2);                                    //Render platform2
  129.         //drawPlatform(platform3);
  130.         //drawPlatform(platform4);
  131.         //drawPlatform(platform5);
  132.     glutSwapBuffers();                                              //Swap buffers
  133. }
  134.  
  135. void update(){glutPostRedisplay();}                                 //Refresh display
  136.  
  137. void runMainLoop(int val){
  138.     update();
  139.     glutTimerFunc(1000/FPS, runMainLoop, val);
  140. }
  141.  
  142. void main (int argc, char** argv){
  143.     glutInit(&argc, argv);
  144.     glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
  145.     glutInitWindowPosition(400, 200);
  146.     glutInitWindowSize(WIN_X, WIN_Y);
  147.     glutCreateWindow("Basic Collision");
  148.     glutTimerFunc(1000/FPS, runMainLoop, 0);
  149.     init();
  150.     glutDisplayFunc(display);
  151.     glutKeyboardFunc(keyPressed);
  152.     glutKeyboardUpFunc(keyUp);
  153.     glutIdleFunc(update);
  154.     glutMainLoop();
  155. }
Advertisement
Add Comment
Please, Sign In to add comment