summaryrefslogtreecommitdiffstats
path: root/src/math/point.ts
blob: 23a0f847fe9cb3658e8a2ce88060ba781b96fdd1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { Collidable } from './collision';
import { Line, Movement, normal } from './line';

import { vec2 } from 'gl-matrix';

export class Point implements Collidable {
	constructor(public readonly p: vec2) {}

	public collide(out: vec2, move: Movement, r: number): boolean {
		const moveLine = move.toLineSegment();

		if (moveLine.projectPointDistance(this.p) < 0)
			return false;

		const d = moveLine.distancePoint(this.p) / r;
		if (Math.abs(d) >= 1)
			return false;

		const e = Math.sqrt(1 - d * d);

		const t = moveLine.getNormal(vec2.create());
		vec2.scale(t, t, d);
		vec2.scaleAndAdd(t, t, moveLine.v, e);

		const tr = vec2.scale(vec2.create(), t, r);

		const refMove = move.translate(tr);

		if (vec2.sqrDist(this.p, move.p1) > r * r && !refMove.passes(this.p))
			return false;

		normal(t, t);

		const tang = new Line(this.p, t);
		tang.projectPoint(out, refMove.p2);
		vec2.sub(out, out, tr);

		return true;
	}
}