Created
July 24, 2020 19:10
-
-
Save steveruizok/c93db0d373be1d9d3c763288e4f5e0e7 to your computer and use it in GitHub Desktop.
Get the point(s) at which a line segment intersects a circle.
This file contains hidden or 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
function getSegmentCircleIntersections( | |
cx: number, | |
cy: number, | |
r: number, | |
x0: number, | |
y0: number, | |
x1: number, | |
y1: number | |
) { | |
var b: number, | |
c: number, | |
d: number, | |
u1: number, | |
u2: number, | |
ret: number[][], | |
retP1: number[], | |
retP2: number[], | |
v1 = [x1 - x0, y1 - y0], | |
v2 = [x0 - cx, y0 - cy]; | |
b = v1[0] * v2[0] + v1[1] * v2[1]; | |
c = 2 * (v1[0] * v1[0] + v1[1] * v1[1]); | |
b *= -2; | |
d = Math.sqrt(b * b - 2 * c * (v2[0] * v2[0] + v2[1] * v2[1] - r * r)); | |
if (isNaN(d)) { | |
// no intercept | |
return []; | |
} | |
u1 = (b - d) / c; // these represent the unit distance of point one and two on the line | |
u2 = (b + d) / c; | |
retP1 = []; // return points | |
retP2 = []; | |
ret = []; // return array | |
if (u1 <= 1 && u1 >= 0) { | |
// add point if on the line segment | |
retP1[0] = x0 + v1[0] * u1; | |
retP1[1] = y0 + v1[1] * u1; | |
ret[0] = retP1; | |
} | |
if (u2 <= 1 && u2 >= 0) { | |
// second add point if on the line segment | |
retP2[0] = x0 + v1[0] * u2; | |
retP2[1] = y0 + v1[1] * u2; | |
ret[ret.length] = retP2; | |
} | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment