86 lines
2.3 KiB
Python
86 lines
2.3 KiB
Python
from pygame import draw, mouse
|
|
from .. import text
|
|
from ..geom.rect import Rect
|
|
from .. import WIDTH, HEIGHT, text
|
|
from ..colors import *
|
|
from ..math import *
|
|
|
|
class AABBDistance:
|
|
|
|
title = "AABB Distance"
|
|
|
|
def render(self, surface):
|
|
rect_a = Rect(
|
|
WIDTH / 2 - (WIDTH / 8),
|
|
HEIGHT / 2 - (HEIGHT / 8),
|
|
WIDTH / 4,
|
|
HEIGHT / 4,
|
|
)
|
|
rect_b = Rect(
|
|
*mouse.get_pos(),
|
|
WIDTH / 5,
|
|
HEIGHT / 5
|
|
)
|
|
|
|
# cx, cy = center
|
|
dist_x = abs(rect_b.cx - rect_a.cx)
|
|
dist_y = abs(rect_b.cy - rect_a.cy)
|
|
|
|
gap_x = dist_x - rect_a.halfwidth - rect_b.halfwidth
|
|
gap_y = dist_y - rect_a.halfheight - rect_b.halfheight
|
|
|
|
distance = 0
|
|
|
|
if gap_x < 0 and gap_y < 0:
|
|
distance = max(gap_x, gap_y)
|
|
else:
|
|
if gap_x < 0:
|
|
distance = gap_y
|
|
elif gap_y < 0:
|
|
distance = gap_x
|
|
else:
|
|
distance = length(gap_x, gap_y)
|
|
|
|
text.draw(surface, (10, HEIGHT - 20), WHITE, f"Distance: {distance}")
|
|
rect_a.draw(surface, YELLOW, 4)
|
|
rect_b.draw(surface, WHITE, 4)
|
|
draw.line(surface, RED if distance < 0 else GREEN,
|
|
rect_a.get_center(), rect_b.get_center(), 2)
|
|
|
|
class PointAABBDistance:
|
|
|
|
title = "Point-AABB Distance"
|
|
|
|
def render(self, surface):
|
|
rect_a = Rect(
|
|
WIDTH / 2 - (WIDTH / 8),
|
|
HEIGHT / 2 - (HEIGHT / 8),
|
|
WIDTH / 4,
|
|
HEIGHT / 4,
|
|
)
|
|
cx, cy = mouse.get_pos()
|
|
|
|
# cx, cy = point
|
|
dist_x = abs(cx - rect_a.cx)
|
|
dist_y = abs(cy - rect_a.cy)
|
|
|
|
gap_x = dist_x - rect_a.halfwidth
|
|
gap_y = dist_y - rect_a.halfheight
|
|
|
|
distance = 0
|
|
|
|
if gap_x < 0 and gap_y < 0:
|
|
distance = max(gap_x, gap_y)
|
|
else:
|
|
if gap_x < 0:
|
|
distance = gap_y
|
|
elif gap_y < 0:
|
|
distance = gap_x
|
|
else:
|
|
distance = length(gap_x, gap_y)
|
|
|
|
text.draw(surface, (10, HEIGHT - 20), WHITE, f"Distance: {distance}")
|
|
rect_a.draw(surface, YELLOW, 4)
|
|
draw.line(surface, RED if distance < 0 else GREEN,
|
|
rect_a.get_center(), (cx, cy), 2)
|