Files
nage/workshop/steps/05-sweep-1d/sweep1d.ts
T
2026-07-11 17:48:28 +02:00

43 lines
869 B
TypeScript

export type Span = { entry: number; exit: number };
/**
* When is a point at `p`, moving by `v` over the frame, inside [min, max]?
*
* Returns the entry/exit times (t, where the position is p + v*t).
* `entry` is always <= `exit`. Values may be < 0 or > 1.
*
* Special case: if v === 0, return {entry:-Infinity, exit:Infinity} when the
* point is already inside [min, max], otherwise return null.
*/
export function sweepInterval(
p: number,
v: number,
min: number,
max: number,
): Span | null {
if (v === 0) {
return isInBetween(p, min, max)
? {
entry: -Infinity,
exit: +Infinity,
}
: null;
}
let t1 = (min - p) / v;
let t2 = (max - p) / v;
if (t1 > t2) {
[t1, t2] = [t2, t1];
}
return {
entry: t1,
exit: t2,
};
}
function isInBetween(p: number, min: number, max: number): boolean {
return min <= p && p <= max;
}