How do you know if two line segments intersect eachother?
If we use this as an example:
from scene import *
def lines_intersect(line1, line2):
# I want this function to return True if line1 intersects with line2
pass
class Test (Scene):
def setup(self):
self.line1 = [400, 600, 500, 600]
self.line2 = [400, 500, 460, 700]
def draw(self):
background(0,0,0)
stroke_weight(5)
stroke(1,0,0)
line(*self.line1)
line(*self.line2)
if lines_intersect(self.line1, self.line2):
print "Yay!"
run(Test())
Update:
This seems to work
def line_intersection(line1, line2):
p1 = Point(line1[0], line1[1])
p2 = Point(line1[2], line1[3])
p3 = Point(line2[0], line2[1])
p4 = Point(line2[2], line2[3])
ans1 = (p2.x-p1.x)*(p3.y-p2.y)-(p2.y-p1.y)*(p3.x-p2.x)
ans2 = (p2.x-p1.x)*(p4.y-p2.y)-(p2.y-p1.y)*(p4.x-p2.x)
ans3 = (p4.x-p3.x)*(p1.y-p4.y)-(p4.y-p3.y)*(p1.x-p4.x)
ans4 = (p4.x-p3.x)*(p2.y-p4.y)-(p4.y-p3.y)*(p2.x-p4.x)
return ((ans1 > 0 and ans2 < 0) or (ans1 < 0 and ans2 > 0) and
(ans3 > 0 and ans4) < 0 or (ans3 < 0 and ans4 > 0))