Skip to content

Instantly share code, notes, and snippets.

@DUznanski
Forked from unstoppablecarl/linesIntersect.js
Created January 6, 2013 03:34
Show Gist options
  • Save DUznanski/4465048 to your computer and use it in GitHub Desktop.
Save DUznanski/4465048 to your computer and use it in GitHub Desktop.
function open_segments_intersect(a1, a2, b1, b2) {
if ((max(a1.x, a2.x) <= min(b1.x, b2.x)) || // a is left of b
(max(b1.x, b2.x) <= min(a1.x, a2.x)) ||
(max(a1.y, a2.y) <= min(b1.y, b2.y)) || // a is above b (in coordinates where (0,0) is topleft)
(max(b1.y, b2.y) <= min(a1.y, a2.y))
) {return false;}
else if ((vcross(vsub(b1,a1),vsub(a2,a1)) * vcross(vsub(b2,a1),vsub(a2,a1)) < 0) && // replace these with <= to make the segments act closed.
(vcross(vsub(a1,b1),vsub(b2,b1)) * vcross(vsub(a2,b1),vsub(b2,b1)) < 0)) {return true;}
else {return false;}
}
function vsub(a, b) {
return {x: a.x - b.x, y, a.y - b.y}
}
function vcross(a, b) {
return a.x * b.y - b.x * a.y;
}
/**
* 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