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)
进入弹壳。
我最近遇到了这个问题,今天遇到了命名元组,所以我想试试:
也可以使用shapely中的多边形(例如具有[x0,y0,x1,y1]的矩形)
可以使用Separating Axis Theorem的简单版本来测试交集。如果矩形不相交,则至少一个右侧将位于另一个矩形左侧的左侧(即,它将是一个分离轴),反之亦然,或者一个顶部将位于另一个矩形的底部下方,反之亦然。
因此,更改测试以检查它们是否不相交:
这段代码假设“top”的y值大于“bottom”(y在屏幕下方减小),因为这就是示例的工作方式。如果你使用的是另一个约定,那么你只需要翻转y比较的符号。
相关问题 更多 >
编程相关推荐