Created
November 5, 2012 03:50
-
-
Save jashkenas/4015219 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var intersect = function(a1, a2, b1, b2) { | |
var ua_t = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x); | |
var ub_t = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x); | |
var u_b = (b2.y - b1.y) * (a2.x - a1.x) - (b2.x - b1.x) * (a2.y - a1.y); | |
if ( u_b != 0 ) { | |
var ua = ua_t / u_b; | |
var ub = ub_t / u_b; | |
if ( 0 <= ua && ua <= 1 && 0 <= ub && ub <= 1 ) { | |
return { | |
x: a1.x + ua * (a2.x - a1.x), | |
y: a1.y + ua * (a2.y - a1.y) | |
}; | |
} else { | |
throw "No Intersection"; | |
} | |
} else { | |
if ( ua_t == 0 || ub_t == 0 ) { | |
throw "Coincident"; | |
} else { | |
throw "Parallel"; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It seems you could benefit from a higher level of abstraction. Something along the lines of