gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:20:53 25 4
gpt4 key购买 nike

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)

进入外壳。

最佳答案

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

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

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 比较的符号即可。

关于python - 使用两个左下角和右上角检查两个矩形在python中是否重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40795709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com