Garret Ulrich Garret Ulrich - 11 days ago 6
Python Question

Checking whether two rectangles overlap in python using two bottom left corners and top right corners

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):


I am trying to see if two triangles intersect based on the upper right and lower left corners however when I make the function:

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


The function will return false when inputting:

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


into the shell.

Answer

You can use a simple version of the Separating Axis Theorem to test for intersection. If the rectangles do not intersect, then at least one of the right sides will be to the left of the left side of the other rectangle (i.e. it will be a separating axis), or vice versa, or one of the top sides will be below the bottom side of the other rectange, or vice versa.

So change the test to check if it is not true that they don't intersect:

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)

This code assumes that the "top" has a greater y value than the "bottom" (y decreases down the screen), because that's how your example seems to work. If you were using the other convention then you'd just flip the signs of the y comparisons.

Comments