geom-demo/geom/demos/aabb.py

92 lines
2.3 KiB
Python
Raw Permalink Normal View History

from pygame import draw
from ..geom import AxisAlignedBB
from .. import WIDTH, HEIGHT, get_cursor_pos
2020-11-13 07:46:31 -07:00
from ..colors import *
from ..math import *
from ..draw import *
2020-11-13 07:46:31 -07:00
class AABBDistance:
title = "AABB Distance"
def handle_key_down(self, key):
pass
2020-11-13 07:46:31 -07:00
def render(self, surface):
rect_a = AxisAlignedBB(
-(WIDTH / 8),
-(HEIGHT / 8),
2020-11-13 07:46:31 -07:00
WIDTH / 4,
HEIGHT / 4,
)
rect_b = AxisAlignedBB(
*get_cursor_pos(),
2020-11-13 07:46:31 -07:00
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, 1)
rect_b.draw(surface, WHITE, 1)
line(surface, RED if distance < 0 else GREEN,
rect_a.get_center(), rect_b.get_center())
2020-11-13 07:46:31 -07:00
class PointAABBDistance:
title = "Point-AABB Distance"
def handle_key_down(self, key):
pass
2020-11-13 07:46:31 -07:00
def render(self, surface):
rect_a = AxisAlignedBB(
-(WIDTH / 8),
-(HEIGHT / 8),
2020-11-13 07:46:31 -07:00
WIDTH / 4,
HEIGHT / 4,
)
cx, cy = get_cursor_pos()
2020-11-13 07:46:31 -07:00
# 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, 1)
line(surface, RED if distance < 0 else GREEN,
rect_a.get_center(), (cx, cy))