2023-03-28 19:35:42 +02:00
|
|
|
import math
|
|
|
|
|
2023-03-29 10:45:48 +02:00
|
|
|
import pygame
|
|
|
|
|
2023-03-28 19:35:42 +02:00
|
|
|
|
2023-03-25 15:41:32 +01:00
|
|
|
class BoundingBox:
|
|
|
|
def __init__(self, x, y, width, height):
|
|
|
|
self.x = x
|
|
|
|
self.y = y
|
|
|
|
self.width = width
|
|
|
|
self.height = height
|
|
|
|
|
2023-03-28 19:35:42 +02:00
|
|
|
self.center_x = x + width / 2
|
|
|
|
self.center_y = y + height / 2
|
|
|
|
|
2023-03-25 15:41:32 +01:00
|
|
|
def get_dimensions(self):
|
|
|
|
return self.width, self.height
|
|
|
|
|
|
|
|
def get_position(self):
|
|
|
|
return self.x, self.y
|
2023-03-25 17:18:43 +01:00
|
|
|
|
2023-03-26 11:13:34 +02:00
|
|
|
def contains_point(self, position: tuple[float, float]):
|
|
|
|
return self.x <= position[0] <= self.x + self.width and self.y <= position[1] <= self.y + self.height
|
|
|
|
|
2023-03-25 17:18:43 +01:00
|
|
|
def __str__(self):
|
|
|
|
return f"({self.x}, {self.y}, {self.width}, {self.height})"
|
2023-03-28 19:35:42 +02:00
|
|
|
|
|
|
|
def distance(self, bounding_box: 'BoundingBox') -> float:
|
|
|
|
"""
|
|
|
|
Classmates the minimum distance between two bounding boxes by checking in what direction the bounding boxes are
|
|
|
|
in relation to each other.
|
|
|
|
:param bounding_box: The bounding box to compare to.
|
|
|
|
:return: The minimum distance between the two bounding boxes.
|
|
|
|
"""
|
|
|
|
if self.overlaps(bounding_box):
|
|
|
|
return 0
|
|
|
|
|
|
|
|
distance_x = max(0, abs(self.center_x - bounding_box.center_x) - (self.width + bounding_box.width) / 2)
|
|
|
|
distance_y = max(0, abs(self.center_y - bounding_box.center_y) - (self.height + bounding_box.height) / 2)
|
|
|
|
|
|
|
|
return math.sqrt(distance_x ** 2 + distance_y ** 2)
|
|
|
|
|
|
|
|
def overlaps(self, bounding_box: 'BoundingBox') -> bool:
|
|
|
|
"""
|
|
|
|
Checks if the bounding boxes overlap.
|
|
|
|
:param bounding_box: The bounding box to check.
|
|
|
|
:return: True if the bounding boxes overlap, False otherwise.
|
|
|
|
"""
|
|
|
|
return self.x < bounding_box.x + bounding_box.width and self.x + self.width > bounding_box.x and \
|
|
|
|
self.y < bounding_box.y + bounding_box.height and self.y + self.height > bounding_box.y
|
2023-03-29 10:45:48 +02:00
|
|
|
|
|
|
|
def get_rect(self) -> pygame.Rect:
|
|
|
|
return pygame.Rect(self.x, self.y, self.width, self.height)
|