Skip to content

Instantly share code, notes, and snippets.

@warmspringwinds
Last active February 4, 2022 21:06
Show Gist options
  • Save warmspringwinds/f3c38ba3d8f0beebd75a59d226e7400e to your computer and use it in GitHub Desktop.
Save warmspringwinds/f3c38ba3d8f0beebd75a59d226e7400e to your computer and use it in GitHub Desktop.
computes intersection between two rectangles
# Assuming the origin is in the top left corner
# x axis facing right
# y axis facing downwards
# r.x, r.y -- are top left corners of the rectangle
# with corresponding r.height and r.width
def intersection_area(r_1, r_2):
intersection = 0.0
left_x = max( r_1.x, r_2.x )
right_x = min( r_1.x + r_1.width, r_2.x + r_2.width )
top_y = max( r_1.y, r_2.y )
bottom_y = min( r_1.y + r_1.height, r_2.y + r_2.height )
if left_x < right_x && top_y < bottom_y:
intersection = (right_x - left_x) * (bottom_y - top_y)
return intersection
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment