I'm having a lot of trouble figuring out what is wrong with my code. Actually, I'm having a very difficult time solving the problem of two rectangles overlapping. The following code should, theoretically, work for the following rectangles:
Rect1: (2.5, 4) width = 2.5, height = 43
Rect2: (1.5, 5) width = 0.5, height = 3
Keep in mind I can't use the Rectangle class to solve this problem. What I've done is calculated the x-values for the left and right edges and the y-values for the top and bottom edges of both rectangles.
I'm first considering -- and I know this does not cover all possible cases -- the scenario in which r2 is within r1.
Note that (x1, y1) and (x2, y2) signify the centers of rectangles 1 and 2, respectively.
right1 = x1 + w1/2;
left1 = x1 - w1/2;
bottom1 = y1 - h1/2;
top1 = y1 + h1/2;
right2 = x2 + w2/2;
left2 = x2 - w2/2;
bottom2 = y2 - h2/2;
top2 = y2 + h2/2;
overlap = ( (right2 < right1 && right2 > left1) &&
(bottom2 > bottom1 && bottom2 < top1) &&
(left2 > left1 && left2 < right1) &&
(top2 < top1 && top2 > bottom1) );
Again, I realize this scenario is not all-encompassing. But even at this point with testing if one rectangle is within another using the above Rect1 and Rect2 values for input, overlap evaluates to false...but it shouldn't -- I've done the math and suggests that the code should work. What did I do wrong?
x1andw2etc look a bit strange. You should ask yourself things like... "Why isright1set tox1 + w1/2? Shouldn't it just bex1 + w1?" With clearer variable names this process will be much more obvious. - byxor