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 许可协议
您可以使用 分离轴定理 的简单版本来测试相交。如果矩形不相交,则至少有一个右侧将位于另一个矩形左侧的左侧(即,它将是一个分离轴),反之亦然,或者顶边之一将是在另一个矩形的底部下方,反之亦然。
因此,更改测试以检查它们是否不相交:
此代码假定“顶部”的 y 值大于“底部”(y 在屏幕下方减小),因为您的示例似乎就是这样工作的。如果您使用的是其他约定,那么您只需翻转 y 比较的符号。