@woosh/meep-engine
Version:
Pure JavaScript game engine. Fully featured and production ready.
51 lines (41 loc) • 1.36 kB
JavaScript
//
import { v3_dot } from "../../vec3/v3_dot.js";
/**
*
* @param {number} center_x
* @param {number} center_y
* @param {number} center_z
* @param {number} radius
* @param {number} origin_x
* @param {number} origin_y
* @param {number} origin_z
* @param {number} direction_x
* @param {number} direction_y
* @param {number} direction_z
* @returns {boolean}
*/
export function sphere_intersects_ray(
center_x, center_y, center_z, radius,
origin_x, origin_y, origin_z,
direction_x, direction_y, direction_z
) {
const delta_x = center_x - origin_x;
const delta_y = center_y - origin_y;
const delta_z = center_z - origin_z;
const tca = v3_dot(delta_x, delta_y, delta_z, direction_x, direction_y, direction_z);
const d2 = v3_dot(delta_x, delta_y, delta_z, delta_x, delta_y, delta_z) - tca * tca;
const radius2 = radius * radius;
if (d2 > radius2) {
return false;
}
const thc = Math.sqrt(radius2 - d2);
// t0 = first intersect point - entrance on front of sphere
const t0 = tca - thc;
// t1 = second intersect point - exit point on back of sphere
const t1 = tca + thc;
// test to see if both t0 and t1 are behind the ray - if so, no intersection
if (t0 < 0 && t1 < 0) {
return false;
}
return true;
}