A rectangle crosses a code. Is it correct?

Can someone tell me if my rectangle intersection 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; } 
+4
source share
4 answers

No, the corner of the rectangle does not have to be in another rectangle to collide the rectangles. What you want to do is find the logic when they don't intersect, and use the negation of it. The figure below shows two rectangles that clearly intersect each other, but only the sides intersect, not the corners.

enter image description here

Just formulate the logic as follows: what is needed so that blue does not intersect red? Well, it's either completely right, completely left, up or down. Formulate an if statement and cancel it. Let me help you from the start:

 if (!(x2 > x+oWidth || x2+o2Width < x || ..)) collide = true; 
+6
source

Following from Magnus' answer, I would take a slightly different approach.

As he says, if these two do not intersect, then they will be completely abandoned, completely right, etc. For performance, however, you can stop testing as soon as any of these conditions is false, for example:

 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... 
+2
source

First set the intersection interval (i.e. one measurement). You can then implement the intersection of the rectangle by first applying the intersection of the intervals to the x-coordinates, and then applying the intersection of the intervals to the y-coordinates.

+1
source
 checkCollide(0, 0, 3, 3, 1, 1, 1, 1) == false 

I guess that is not what you want.

0
source

All Articles