java - Two overlapping rectangles -


i'm having lot of trouble figuring out wrong code. actually, i'm having difficult time solving problem of 2 rectangles overlapping. following code should, theoretically, work following rectangles:

rect1: (2.5, 4) width = 2.5, height = 43

rect2: (1.5, 5) width = 0.5, height = 3

keep in mind can't use rectangle class solve problem. i've done calculated x-values left , right edges , y-values top , bottom edges of both rectangles.

i'm first considering -- , know not cover possible cases -- scenario in r2 within r1.

note (x1, y1) , (x2, y2) signify centers of rectangles 1 , 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, realize scenario not all-encompassing. @ point testing if 1 rectangle within using above rect1 , rect2 values input, overlap evaluates false...but shouldn't -- i've done math , suggests code should work. did wrong?

rectangles overlapping if there intersection between both horizontal , vertical sides - it's case of checking whether 2 lines overlap each dimension.

the check whether line x1 -> x2 overlaps line x3 -> x4 whether first line starts before end of second , ends after start, or in code:

x1 <= x4 && x2 >= x3 

to translate rectangles, apply test both dimensions:

(x1 <= x4 && x2 >= x3) && (y1 <= y4 && y2 >= y3) 

..where 1 rectangle x1,y1 -> x2,y2 , other x3,y3 -> x4,y4 (easily calculated start position , width).


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

mapreduce - Resource manager does not transit to active state from standby -

serialization - Convert Any type in scala to Array[Byte] and back -