intersect line

This commit is contained in:
Frank DeMarco 2015-07-02 16:44:29 -04:00
parent 41b94cf35b
commit 8a541bbddf
2 changed files with 41 additions and 1 deletions

View File

@ -62,7 +62,7 @@ class Delegate(GameChild):
self.subscribers[kind].remove(callback)
def compare(self, evt, commands=None, cancel=False, **attributes):
if evt.type == self.command_event_id:
if self.is_command(evt):
self.add_cancel_flag_to_attributes(attributes, cancel)
if commands is not None and not isinstance(commands, list):
commands = [commands]

View File

@ -58,3 +58,43 @@ def place_in_rect(rect, incoming, contain=True, *args):
break
if not collides:
break
def get_intersection(p0, p1, p2, p3):
x0, y0 = p0
x1, y1 = p1
x2, y2 = p2
x3, y3 = p3
a0 = y1 - y0
b0 = x0 - x1
c0 = x1 * y0 - x0 * y1
r2 = a0 * x2 + b0 * y2 + c0
r3 = a0 * x3 + b0 * y3 + c0
if r2 != 0 and r3 != 0 and r2 * r3 > 0:
return None
a1 = y3 - y2
b1 = x2 - x3
c1 = x3 * y2 - x2 * y3
r0 = a1 * x0 + b1 * y0 + c1
r1 = a1 * x1 + b1 * y1 + c1
if r0 != 0 and r1 != 0 and r0 * r1 > 0:
return None
denominator = a0 * b1 - a1 * b0
if denominator == 0:
return (x0 + x1 + x2 + x3) / 4, (y0 + y1 + y2 + y3) / 4
if denominator < 0:
offset = -denominator / 2
else:
offset = denominator / 2
numerator = b0 * c1 - b1 * c0
x = ((-1, 1)[numerator < 0] * offset + numerator) / denominator
numerator = a1 * c0 - a0 * c1
y = ((-1, 1)[numerator < 0] * offset + numerator) / denominator
return x, y
def collide_line_with_rect(rect, p0, p1):
for line in ((rect.topleft, rect.topright),
(rect.topright, rect.bottomright),
(rect.bottomright, rect.bottomleft),
(rect.bottomleft, rect.topleft)):
if get_intersection(p0, p1, *line):
return True