Skip to content

Instantly share code, notes, and snippets.

@steveruizok
Last active October 10, 2021 11:46
Show Gist options
  • Save steveruizok/baa0aff8ec5935e99c8ef036be56e035 to your computer and use it in GitHub Desktop.
Save steveruizok/baa0aff8ec5935e99c8ef036be56e035 to your computer and use it in GitHub Desktop.
Get the intersection of two rays.
/**
* Get the intersection of two rays, with origin points p0 and p1, and direction vectors n0 and n1.
* @param p0 The origin point of the first ray
* @param n0 The direction vector of the first ray
* @param p1 The origin point of the second ray
* @param n1 The direction vector of the second ray
* @returns
*/
export function getRaysIntersection(
p0: number[],
n0: number[],
p1: number[],
n1: number[]
): number[] | undefined {
const dx = p1[0] - p0[0];
const dy = p1[1] - p0[1];
const det = n1[0] * n0[1] - n1[1] * n0[0];
const u = (dy * n1[0] - dx * n1[1]) / det;
const v = (dy * n0[0] - dx * n0[1]) / det;
if (u < 0 || v < 0) return undefined; // Might intersect as lines, but not as rays.
const m0 = n0[1] / n0[0];
const m1 = n1[1] / n1[0];
const b0 = p0[1] - m0 * p0[0];
const b1 = p1[1] - m1 * p1[0];
const x = (b1 - b0) / (m0 - m1);
const y = m0 * x + b0;
return Number.isFinite(x) ? [x, y] : undefined;
}
@steveruizok
Copy link
Author

Probably useful too: a helper to get a normalized direction vector between two points.

function getDirectionVector(x0: number, y0: number, x1: number, y1: number) {
  const dx = x1 - x0
  const dy = y1 - y0
  const l = Math.hypot(dy, dx)
  return [dx / l, dy / l]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment