so im writing a program to test if rectangles intersect... im given x,y,width and length of each rectangle.. so far i have this calculation but in some cases its right and then some is incorrect!
anybody know what im doing wrong?
class Rectangle{
public:
int x, y;
int width;
int length;
Rectangle(int x1, int y1, int w, int l)//Constructor
{
x = x1;
y = y1;
width = w;
length = l;
}
bool intersect(Rectangle r1, Rectangle r2)
{
// x1, y1, w1, L1........ x2, y2, w2, L2
//If X1+H1<X2 or X2+H2<X1 or Y1+W1<Y2 or Y2+W2<Y1
1 and 5 obviously do.
2 and 4 obviously do not.
3 does -- maybe (depends on how you define the intersection).
Your choice on how to handle pair-3 will affect your algorithm:
If pair-3 does intersect, then all you need to check is if any corner of either rectangle is inside the area of the other rectangle (or on the edge line).
If pair-3 does not intersect, then you must also test that at least one other corner of the rectangle is not inside the area of the other rectangle.
Oops! I knew I was leaving something out...
Yes, the cross is a special case not handled by my algorithm... Solve it and you'll get a better algorithm...
LOL! Duoas, that is probably the most thoughtful and selfless post I have ever seen. I mean, you actually drew 10 rectangles in text to demonstrate this. The OP should be kissing your @ss! :-) Kudos for being so darn helpful!
@ OP: If you don't need an algorithm, just results, and you are using Windows, you can use the regions API to find out if the rectangles intersect. Just saying! :-P