Last active
October 10, 2021 11:46
-
-
Save steveruizok/baa0aff8ec5935e99c8ef036be56e035 to your computer and use it in GitHub Desktop.
Get the intersection of two rays.
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
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Probably useful too: a helper to get a normalized direction vector between two points.