开发者

Calculate overlap between two rectangles on x/y grid?

I need to calculate the overlap (amount or yes/no) that two rectangles make on a special x/y grid. The grid is 500x500 but the sides and corners connect (are continuous). So the next point after 499 becomes 0 again.

In a previous question I asked for a way to calculate the distance between two points in this grid. This turned out to be the Euclidean distance:

sqrt(min(|x1 - x2|, gridwidth - |x1 - x2|)^2 + min(|y1 - y2|, gridheight - |y1-y2|)^2)

What is the good mathema开发者_Python百科tical way of calculating if two rectangles (defined by a point (x,y), width and height) have overlap in this grid?

Rectangle-1 ([x=0,y=0], w=20, h=20) and Rectangle-2 ([x=495,y=0], w=10, h=10) should have overlap. The overlapping rectangle (not really needed but) should be ([x=0,y=0], w=5, h=10)


First, compute the x and y range for each rectangle (because you have a torus geometry do it mod gridsize).

So, given your Rectangle-1, compute:

x1 = x = 0, x2 = x + w = 20
y1 = y = 0, y2 = y + h = 20

Same for Rectangle-2:

x3 = 495, x4 = 505 mod 500 = 5
y3 = 0,   y4 = 10

Create the x and y "regions" for each rectangle:

Reactangle-1: x-regions: (0, 20)
              y-regions: (0, 20)

Rectangle-2:  x-regions: (495, 500), (0, 5)
              y-regions: (0, 10)

If any (both) x and y regions between the two rectangles have a non-null intersection, then your rectangles overlap. Here the (0, 20) x-region of Rectangle-1 and the (0, 5) x-region of Rectangle-2 have a non-null intersection and so do the (0, 20) and (0, 10) y-regions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜