Created
January 14, 2015 07:35
-
-
Save PAEz/a4dc5742d4443e54e4ad to your computer and use it in GitHub Desktop.
Check Line Intersection
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
// http://jsfiddle.net/justin_c_rounds/Gd2S2/ | |
function checkLineIntersection(startX1, startY1, endX1, endY1, startX2, startY2, endX2, endY2, result) { | |
// if the lines intersect, the result contains the x and y of the intersection (treating the lines as infinite) and booleans for whether line segment 1 or line segment 2 contain the point | |
var denominator, a, b, numerator1, numerator2, result = result || { | |
x: 0, | |
y: 0, | |
onLine1: false, | |
onLine2: false | |
}; | |
denominator = ((endY2 - startY2) * (endX1 - startX1)) - ((endX2 - startX2) * (endY1 - startY1)); | |
if (denominator == 0) { | |
result.x=0; | |
result.y=0; | |
result.onLine2=false; | |
result.onLine1=false; | |
return result; | |
} | |
a = startY1 - startY2; | |
b = startX1 - startX2; | |
numerator1 = ((endX2 - startX2) * a) - ((endY2 - startY2) * b); | |
numerator2 = ((endX1 - startX1) * a) - ((endY1 - startY1) * b); | |
a = numerator1 / denominator; | |
b = numerator2 / denominator; | |
result.x = startX1 + (a * (endX1 - startX1)); | |
result.y = startY1 + (a * (endY1 - startY1)); | |
result.onLine1 = a > 0 && a < 1; | |
result.onLine2 = b > 0 && b < 1; | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I had hassles finding a routine like this one that worked, this one seems to work well.
I only changed it to let you pass in the result object so it doesnt have to create it each time, this can speed things up if your checking thousands of lines and dont need to store the result object.