Advertisement
Archon

circleCollision

Jun 24th, 2012
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.07 KB | None | 0 0
  1. //whether a circle and a rectangle collide
  2. bool circleCollision(const Location &center, double radius, const SDL_Rect &rect){
  3.    // test 1 && (test 2 || test 3)
  4.  
  5.    double
  6.       left = rect.x,
  7.       right = left + rect.w,
  8.       top = rect.y,
  9.       bottom = top + rect.h,
  10.  
  11.       centerX = center.x,
  12.       centerY = center.y;
  13.  
  14.    //test 1: the rectangles must collide, and
  15.    if (centerX - radius > right ||
  16.        centerX + radius < left ||
  17.        centerY - radius > bottom ||
  18.        centerY + radius < top)
  19.       return false;
  20.  
  21.    //test 2: the center must be between the left-right or top-bottom edges of the rectangle, or
  22.    if (centerX > left && centerX < right) ||
  23.        centerY > top && centerY < bottom)
  24.       return true;
  25.  
  26.    //test 3: at least one corner must be within circle
  27.    if (distance(top, left, centerX, centerY) < radius ||
  28.        distance(top, right, centerX, centerY) < radius ||
  29.        distance(bottom, left, centerX, centerY) < radius ||
  30.        distance(bottom, right, centerX, centerY) < radius)
  31.       return true;
  32.  
  33.    return false;
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement