Skip to content

Instantly share code, notes, and snippets.

@iaincarsberg
Created September 28, 2011 09:30
Show Gist options
  • Save iaincarsberg/1247466 to your computer and use it in GitHub Desktop.
Save iaincarsberg/1247466 to your computer and use it in GitHub Desktop.
The lineIntersection function from the thorny/math/poly2.js class file
/**
* Used to find an intersection between two points.
* @param vector2
* @return obj|false if intersection happened returns array of x/y
* otherwise fales.
*/
lineIntersection: function (v1, v2, v3, v4) {
var
bx,
by,
dx,
dy,
b_dot_d_perp,
cx,
cy,
t,
u;
bx = v2.getX() - v1.getX();
by = v2.getY() - v1.getY();
dx = v4.getX() - v3.getX();
dy = v4.getY() - v3.getY();
b_dot_d_perp = bx * dy - by * dx;
if (b_dot_d_perp === 0) {
return false;
}
cx = v3.getX() - v1.getX();
cy = v3.getY() - v1.getY();
t = (cx * dy - cy * dx) / b_dot_d_perp;
if (t < 0 || t > 1) {
return false;
}
u = (cx * by - cy * bx) / b_dot_d_perp;
if (u < 0 || u > 1) {
return false;
}
return vector2(v1.getX() + t * bx, v1.getY() + t * by);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment