Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rectangle intersect code - Is this right?

Tags:

c++

Can someone tell me whether my rectangle intersect code is correct?

bool checkCollide(int x, int y, int oWidth, int oHeight,
                  int x2, int y2, int o2Width, int o2Height) {

   bool collide = false;

   if (x >= x2 && x <= x2+o2Width && y >= y2 && y <= y2+o2Height)
      collide = true;

   if (x+oWidth >= x2 && x+oWidth <= x2+o2Width && y >= y2 && y <= y2+o2Height)
      collide = true;

   if (x >= x2 && x<= x2+o2Width && y+oHeight >= y2 && y+oHeight <= y2+o2Height)
      collide = true;

   if (x+oWidth >= x2 && x+oWidth <= x2+o2Width && y+oHeight >= y2 && y+oHeight <= y2+o2Height)
      collide = true;

   return collide;
}
like image 954
Peace Avatar asked Jan 20 '23 16:01

Peace


2 Answers

Nope, a corner of a rectangle doesn't have to be in the other rectangle for the rectangles to collide. What you want to do is to find the logic when they do not intersect and use the negation of that. The picture below shows two rectangles that clearly intersect each other, but only the sides are intersecting, not the corners.

enter image description here

Just formulate the logic as follows: What does it take for the blue to not intersect the red? Well it's either completely to the right, completely to the left, up or below. Formulate an if statement to that and negate it. Let me help you with the beginning:

if (!(x2 > x+oWidth || x2+o2Width < x || ..))
      collide = true;
like image 91
ralphtheninja Avatar answered Jan 28 '23 03:01

ralphtheninja


Following on from Magnus's answer, I'd take a slightly different approach.

As he says, if the two don't intersect then one will be completely left, completely right, etc. For performance however you can stop testing as soon as any of these conditions are found to be false, e.g.:

if (x2 + owidth2 < x) 
    return false;  // box 2 is left of box 1

if (x + owidth < x2)
    return false;  // box 1 is left of box 2

// etc...
like image 42
Alnitak Avatar answered Jan 28 '23 03:01

Alnitak