Skip to content

Instantly share code, notes, and snippets.

@unstoppablecarl
Last active December 10, 2015 16:59
Show Gist options
  • Save unstoppablecarl/4464799 to your computer and use it in GitHub Desktop.
Save unstoppablecarl/4464799 to your computer and use it in GitHub Desktop.
/**
* checks if 2 lines intersect TESTED
* coincidentReturn: what to return if lines are coincident (exactly overlaping)
* parallelReturn: what to return if lines are exactly parallel
*/
linesIntersect = function (a1, a2, b1, b2, coincidentReturn, parallelReturn){
var result,
coincidentReturn = coincidentReturn || false,
parallelReturn = parallelReturn || false,
ua_t = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x),
ub_t = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x),
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 ) {
//Intersection
return true;
} else {
//No Intersection
return false;
}
} else {
if ( ua_t == 0 || ub_t == 0 ) {
//Coincident
return coincidentReturn;
} else {
//Parallel
return parallelReturn;
}
}
return result;
}
/**
* checks if a point is inside of a concave or convex polygon TESTED
* polygon: array of {x:1, y: 1} objects
*/
pointInPolygon = function (point, polygon){
var i,
j,
c = 0,
pointX = point.x,
pointY = point.y;
for (i = 0, j = polygon.length - 1, len = polygon.length; i < len; j = i++){
if (((polygon[i].y > pointY) != (polygon[j].y > pointY)) && (pointX < (polygon[j].x - polygon[i].x) * (pointY - polygon[i].y) / (polygon[j].y - polygon[i].y) + polygon[i].x)){
c = !c;
}
}
return c;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment