使用两个左下角和右上角检查两个矩形在python中是否重叠

新手上路,请多包涵
class Point:

    def __init__(self, xcoord=0, ycoord=0):
        self.x = xcoord
        self.y = ycoord

class Rectangle:
    def __init__(self, bottom_left, top_right, colour):
        self.bottom_left = bottom_left
        self.top_right = top_right
        self.colour = colour

    def intersects(self, other):

我试图查看两个矩形是否基于右上角和左下角相交,但是当我创建函数时:

 def intersects(self, other):
    return self.top_right.x>=other.top_right.x>=self.bottom_left.x and self.top_right.x>=other.bottom_left.x>=self.bottom_left.x and self.top_right.y>=other.top_right.y>=self.bottom_left.y and self.top_right.x>=other.bottom_left.x>=self.bottom_left.x

该函数将在输入时返回 false:

 r1=Rectangle(Point(1,1), Point(2,2), 'blue')
r3=Rectangle(Point(1.5,0), Point(1.7,3), 'red')
r1.intersects(r3)

进入外壳。

原文由 Garret Ulrich 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 628
2 个回答

您可以使用 分离轴定理 的简单版本来测试相交。如果矩形不相交,则至少有一个右侧将位于另一个矩形左侧的左侧(即,它将是一个分离轴),反之亦然,或者顶边之一将是在另一个矩形的底部下方,反之亦然。

因此,更改测试以检查它们是否不相交:

 def intersects(self, other):
    return not (self.top_right.x < other.bottom_left.x or self.bottom_left.x > other.top_right.x or self.top_right.y < other.bottom_left.y or self.bottom_left.y > other.top_right.y)

此代码假定“顶部”的 y 值大于“底部”(y 在屏幕下方减小),因为您的示例似乎就是这样工作的。如果您使用的是其他约定,那么您只需翻转 y 比较的符号。

原文由 samgak 发布,翻译遵循 CC BY-SA 3.0 许可协议

我最近遇到了这个问题,今天遇到了命名元组,所以我想试试看:

 from collections import namedtuple

RECT_NAMEDTUPLE = namedtuple('RECT_NAMEDTUPLE', 'x1 x2 y1 y2')

Rect1 = RECT_NAMEDTUPLE(10,100,40,80)
Rect2 = RECT_NAMEDTUPLE(20,210,10,60)

def overlap(rec1, rec2):
  if (rec2.x2 > rec1.x1 and rec2.x2 < rec1.x2) or \
     (rec2.x1 > rec1.x1 and rec2.x1 < rec1.x2):
    x_match = True
  else:
    x_match = False
  if (rec2.y2 > rec1.y1 and rec2.y2 < rec1.y2) or \
     (rec2.y1 > rec1.y1 and rec2.y1 < rec1.y2):
    y_match = True
  else:
    y_match = False
  if x_match and y_match:
    return True
  else:
    return False

print ("Overlap found?", overlap(Rect1, Rect2))

Overlap found? True

原文由 mobime 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题