summaryrefslogtreecommitdiffstats
path: root/src/math/line.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/math/line.ts')
-rw-r--r--src/math/line.ts61
1 files changed, 14 insertions, 47 deletions
diff --git a/src/math/line.ts b/src/math/line.ts
index d071779..d29bc76 100644
--- a/src/math/line.ts
+++ b/src/math/line.ts
@@ -1,4 +1,5 @@
import { mat2, vec2 } from 'gl-matrix';
+import { Collidable } from './collision';
const rot90 = mat2.fromValues(
0, 1,
@@ -80,7 +81,7 @@ export class Movement {
}
}
-export class LineSegment extends Line {
+export class LineSegment extends Line implements Collidable {
public static fromPoints(p1: vec2, p2: vec2): LineSegment {
const d = vec2.dist(p1, p2);
const v = vec2.sub(vec2.create(), p2, p1);
@@ -101,70 +102,36 @@ export class LineSegment extends Line {
return vec2.scaleAndAdd(out, this.p, this.v, this.l);
}
- public collidesPoint(p2: vec2): boolean {
+ public containsPoint(p2: vec2): boolean {
const d = this.projectPointDistance(p2);
return (d >= 0 && d <= this.l);
}
- public collidesMove(out: vec2, move: Movement): boolean {
- if (this.distancePoint(move.p1) < 0)
- return false;
-
- if (this.distancePoint(move.p2) >= 0)
- return false;
-
- const x = move.intersectLine(vec2.create(), this);
- if (!this.collidesPoint(x))
- return false;
-
- this.projectPoint(out, move.p2);
-
- return true;
- }
-
- public collidesMoveCircle(out: vec2, move: Movement, r: number): boolean {
+ public collide(out: vec2, move: Movement, r: number): boolean {
const t = this.getNormal(vec2.create());
vec2.scale(t, t, -r);
const refMove = move.translate(t);
- const refOut = vec2.create();
- if (this.collidesMove(refOut, refMove)) {
- vec2.sub(out, refOut, t);
- return true;
- }
+ if (!this.collideRef(out, refMove))
+ return false;
- return this.collidesPointMoveCircle(out, move, r);
+ vec2.sub(out, out, t);
+ return true;
}
- private collidesPointMoveCircle(out: vec2, move: Movement, r: number): boolean {
- const moveLine = move.toLineSegment();
-
- if (moveLine.projectPointDistance(this.p) < 0)
+ private collideRef(out: vec2, move: Movement): boolean {
+ if (this.distancePoint(move.p1) < 0)
return false;
- const d = moveLine.distancePoint(this.p) / r;
- if (Math.abs(d) >= 1)
+ if (this.distancePoint(move.p2) >= 0)
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))
+ const x = move.intersectLine(vec2.create(), this);
+ if (!this.containsPoint(x))
return false;
- normal(t, t);
-
- const tang = new Line(this.p, t);
- tang.projectPoint(out, refMove.p2);
- vec2.sub(out, out, tr);
+ this.projectPoint(out, move.p2);
return true;
}