collision detection!

anybody have luck finding a formula to see if 2 rectangles intersept?

mine doesnt work

if((r1.x+r1.length < r2.x) || (r2.x+r2.length < r1.x) || (r1.y+r1.width < r2.y) || (r2.y+r2.width < r1.y)){
return true;
}
else {
return false;
}
assuming you have l, r, t, b members (left, right, top, bottom), and assuming positive y is downward....


1
2
3
4
5
6
if(r1.r < r2.l)  return false;
if(r1.l > r2.r)  return false;
if(r1.b < r2.t)  return false;
if(r1.t > r2.b)  return false;

return true;
how about if you have x,y,width, length???
right_side_of_rectangle=left_side+width
If the rectangles are axis aligned, it's simple:

1
2
3
4
5
6
7
8
9
10
11
12
13
/* assuming Rectangle with members x,y,width,height, also assuming that x and y denote the center of the rectangle */

bool intersect(const Rectangle& rectangle1, const Rectangle& rectangle2)
{
   if(abs(rectangle1.x-rectangle2.x)<(rectangle1.width/2+rectangle2.width/2)
   {
      if(abs(rectangle1.y-rectangle2.y)<(rectangle1.height/2+rectangle2.height/2)
      {
             return true;
      }
   }
return false;
}


If the rectangles are NOT axis aligned, you'd have to go for a more general solution like SAT.
Last edited on
Topic archived. No new replies allowed.