Skip to content

Instantly share code, notes, and snippets.

@mekkablue
Last active August 29, 2015 13:59
Show Gist options
  • Save mekkablue/10493035 to your computer and use it in GitHub Desktop.
Save mekkablue/10493035 to your computer and use it in GitHub Desktop.
def intersect( x1, y1, x2, y2, x3, y3, x4, y4 ):
"""Calculates the intersection of line P1-P2 with P3-P4."""
slope12 = ( float(y2) - float(y1) ) / ( float(x2) - float(x1) )
slope34 = ( float(y4) - float(y3) ) / ( float(x4) - float(x3) )
x = ( slope12 * x1 - y1 - slope34 * x3 + y3 ) / ( slope12 - slope34 )
y = slope12 * ( x - x1 ) + y1
return x, y
# this also tests for vertical slopes:
def intersectionWithNSPoints( pointA, pointB, pointC, pointD ):
"""
Returns an NSPoint of the intersection AB with CD.
Or False if there is no intersection
"""
try:
x1, y1 = pointA.x, pointA.y
x2, y2 = pointB.x, pointB.y
x3, y3 = pointC.x, pointC.y
x4, y4 = pointD.x, pointD.y
try:
slope12 = ( float(y2) - float(y1) ) / ( float(x2) - float(x1) )
except:
slope12 = None # vertical
try:
slope34 = ( float(y4) - float(y3) ) / ( float(x4) - float(x3) )
except:
slope34 = None # vertical
if slope12 == slope34:
# parallel, no intersection
return False
elif slope12 is None:
# first line is vertical
x = x1
y = slope34 * ( x - x3 ) + y3
elif slope34 is None:
# second line is vertical
x = x3
y = slope12 * ( x - x1 ) + y1
else:
# both lines have an angle
x = ( slope12 * x1 - y1 - slope34 * x3 + y3 ) / ( slope12 - slope34 )
y = slope12 * ( x - x1 ) + y1
return NSPoint( x, y )
except Exception as e:
print str(e)
return False
@bennibaermann
Copy link

Könnte es vielleicht sein, dass die Funktion den Schnittpunkt der beiden Geraden berechnet, also auch wenn der hinter AB/CD liegt true liefert? ich werd mal versuchen noch ne extraabfrage dahinter einzubauen...

@bennibaermann
Copy link

Hm, tut immer noch nich :( Der findet irgendwelche Schnittpunkte, aber nich die richtigen. Falls es Dich interessiert, hier der Kontext: https://github.com/bennibaermann/maximetro trotzdem Danke nochmal für die Hilfe, Fehler liegt bestimmt bei mir.

@bennibaermann
Copy link

so, habs doch noch hingekriegt. vielleicht nich auf die schönste art, aber es wirkt :) Danke!

@mekkablue
Copy link
Author

slope12 == slope34, wenn sie parallel sind, also bei den Divisionen oben dasselbe rauskommt. Das kann ein Zahlenwert sein oder zweimal False.

@bennibaermann
Copy link

ja, klar. der witz ist nur, dass ich ja nicht den schnittpunkt zweier gerade gesucht hab, sondern zweier strecken. hab das dann aber einfach hinterher noch abgefragt, das ging dann.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment