thecplusplusguy

Simple pong game (SDL) - ball.cpp

Jul 4th, 2011
1,679
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. //Simple pong game - ball.cpp
  2. //created by thecplusplusguy
  3. //     http://www.youtube.com/user/thecplusplusguy
  4. #include "ball.h"
  5.  
  6. ball::ball(SDL_Surface* img,int x,int y,int w,int h,int xVel,int yVel)
  7. {
  8.     image=img;
  9.     box.x=x;
  10.     box.y=y;
  11.     box.w=w;
  12.     box.h=h;
  13.     xvel=xVel;
  14.     yvel=yVel;
  15. }
  16.  
  17. ball::~ball()
  18. {
  19.     SDL_FreeSurface(image);
  20. }
  21.  
  22. void ball::show()
  23. {
  24.     SDL_BlitSurface(image,NULL,SDL_GetVideoSurface(),&box);
  25. }
  26.  
  27. void ball::move(SDL_Rect* player1,SDL_Rect* player2,Mix_Chunk* effect)
  28. {
  29.     box.x+=xvel;
  30.     box.y+=yvel;
  31.     if(box.y<=0)
  32.         yvel=-yvel;
  33.     if(box.y+box.h>=SDL_GetVideoSurface()->clip_rect.h)
  34.         yvel=-yvel;
  35.     if(collision(&box,player1))
  36.     {
  37.         Mix_PlayChannel(-1,effect,0);
  38.         if(box.x+3<player1->x+player1->w)
  39.             yvel=-yvel;
  40.         else
  41.             xvel=-xvel;
  42.     }
  43.     if(collision(&box,player2))
  44.     {
  45.         Mix_PlayChannel(-1,effect,0);
  46.         if(box.x+box.w-3 > player2->x)
  47.             yvel=-yvel;
  48.         else
  49.             xvel=-xvel;
  50.  
  51.     }
  52. }
  53.  
  54. bool ball::collision(SDL_Rect* rec1,SDL_Rect* rec2)
  55. {
  56.     if(rec1->y >= rec2->y + rec2->h)
  57.         return 0;
  58.     if(rec1->x >= rec2->x + rec2->w)
  59.         return 0;
  60.     if(rec1->y + rec1->h <= rec2->y)
  61.         return 0;
  62.     if(rec1->x + rec1->w <= rec2->x)
  63.         return 0;
  64.     return 1;
  65. }
  66.  
  67.  
  68. int ball::isOut()
  69. {
  70.     if(box.x<=0)
  71.         return 1;
  72.     if(box.x>=SDL_GetVideoSurface()->clip_rect.w)
  73.         return 2;
  74.     return 0;
  75. }
  76.  
  77.  
  78. void ball::setBack(int x,int y,int w,int h,int xVel,int yVel)
  79. {
  80.     box.x=x;
  81.     box.y=y;
  82.     box.w=w;
  83.     box.h=h;
  84.     xvel=xVel;
  85.     yvel=yVel;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment