geom-demo/geom/demos/aabb.py

86 lines
2.3 KiB
Python

from pygame import draw
from ..geom import AxisAlignedBB
from .. import WIDTH, HEIGHT, get_cursor_pos
from ..colors import *
from ..math import *
from ..draw import *
class AABBDistance:
title = "AABB Distance"
def render(self, surface):
rect_a = AxisAlignedBB(
-(WIDTH / 8),
-(HEIGHT / 8),
WIDTH / 4,
HEIGHT / 4,
)
rect_b = AxisAlignedBB(
*get_cursor_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_screen(surface, WHITE, (10, HEIGHT - 20), f"Distance: {distance}")
rect_a.draw(surface, YELLOW, 4)
rect_b.draw(surface, WHITE, 4)
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 = AxisAlignedBB(
-(WIDTH / 8),
-(HEIGHT / 8),
WIDTH / 4,
HEIGHT / 4,
)
cx, cy = get_cursor_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_screen(surface, WHITE, (10, HEIGHT - 20), f"Distance: {distance}")
rect_a.draw(surface, YELLOW, 4)
line(surface, RED if distance < 0 else GREEN,
rect_a.get_center(), (cx, cy), 2)