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;
}
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.
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;
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With