Advertisement
Guest User

ball collision!?

a guest
Nov 26th, 2014
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. /*
  2. * Ball.cpp
  3. *
  4. * Created on: Nov 21, 2014
  5. * Author: Austin
  6. *
  7. * Creates ball texture, when goes out of bounds, restarts back at center, launches in a random direction, collides with
  8. * bottom and top of window with the opposite direction of velocity.
  9. */
  10. #include <iostream>
  11. #include <ctime>
  12. #include <stdlib.h>
  13. #include <SDL_image.h>
  14. using namespace std;
  15. #include "Ball.h"
  16.  
  17. Ball::Ball(SDL_Renderer *renderBall, string filePath, int x, int y)
  18. {
  19. SDL_Surface *surface = IMG_Load(filePath.c_str());
  20. if(surface == NULL)
  21. cout << "Error ball surface" << endl;
  22. else
  23. {
  24. texture = SDL_CreateTextureFromSurface(renderBall, surface);
  25. if(texture == NULL)
  26. cout << "Error ball texture" << endl;
  27. }
  28.  
  29. SDL_FreeSurface(surface);
  30.  
  31. ballRect.x = x;
  32. ballRect.y = y;
  33.  
  34. posRect.w = 14;
  35. posRect.h = 14;
  36.  
  37. ballRect.w = posRect.w;
  38. ballRect.h = posRect.h;
  39.  
  40. xVel = -1;
  41. yVel = 3;
  42.  
  43. SDL_QueryTexture(texture, NULL, NULL, &posRect.w, &posRect.h);
  44. }
  45.  
  46. void Ball::UpdateBall(float delta)
  47. {
  48. //Ball::RandomNumber = srand(time(NULL));
  49. //Collision detection
  50.  
  51. ballRect.x += xVel;
  52. ballRect.y += yVel;
  53.  
  54. if(ballRect.y < 0)
  55. yVel = -yVel;
  56. if(ballRect.y > 586)
  57. yVel = -yVel;
  58.  
  59. if(ballRect.x + ballRect.w > posRect.x && ballRect.x < posRect.x + posRect.w)
  60. {
  61. if(ballRect.y + ballRect.h > posRect.y && ballRect.y < posRect.y + posRect.w)
  62. {
  63. xVel = -xVel;
  64. }
  65. }
  66. }
  67.  
  68. Ball::~Ball()
  69. {
  70. SDL_DestroyTexture(texture);
  71. }
  72.  
  73. int GetRandomNumber(int high, int low)
  74. {
  75. return rand() % high + low;
  76. }
  77.  
  78. void Ball::Draw(SDL_Renderer *renderBall)
  79. {
  80. SDL_RenderCopy(renderBall, texture, NULL, &ballRect);
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement