Skip to content

Instantly share code, notes, and snippets.

@nkt1546789
Last active August 29, 2015 14:12
Show Gist options
  • Save nkt1546789/0522370b93e8765a9afd to your computer and use it in GitHub Desktop.
Save nkt1546789/0522370b93e8765a9afd to your computer and use it in GitHub Desktop.
線分の交差判定 (Test whether line segments are intersected) on Python
def intersected(a,b,c,d):
x1=b[0]-a[0]
x2=c[0]-d[0]
x3=b[1]-a[1]
x4=c[1]-d[1]
d=float(x1*x4-x2*x3)
if d==0: return False
c1=c[0]-a[0]
c2=c[1]-a[1]
s=(c1*x4-c2*x2)/d
t=(c2*x1-c1*x3)/d
if 0<=s<=1 and 0<=t<=1: return True
return False
if __name__ == "__main__":
# should be intersected
a,b=(-3,1),(3,1)
c,d=(-2,2),(-2,-1)
print intersected(a,b,c,d)
# should not be intersected
a,b=(-3,1),(3,1)
c,d=(2,-1),(-2,-1)
print intersected(a,b,c,d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment