herd / files / src / math / Vec2.ts
Vec2.ts
5edd30c7 2026-05-17 Pavel Safronov | 1 | export class Vec2 { |
| 2 | readonly x: number | |
| 3 | readonly y: number | |
| 4 | constructor(x: number, y: number) { this.x = x; this.y = y } | |
| 5 | ||
| 6 | add(v: Vec2): Vec2 { return new Vec2(this.x + v.x, this.y + v.y) } | |
| 7 | sub(v: Vec2): Vec2 { return new Vec2(this.x - v.x, this.y - v.y) } | |
| 8 | scale(s: number): Vec2 { return new Vec2(this.x * s, this.y * s) } | |
| 9 | ||
| 10 | length(): number { return Math.sqrt(this.x * this.x + this.y * this.y) } | |
| 11 | lengthSq(): number { return this.x * this.x + this.y * this.y } | |
| 12 | ||
| 13 | normalize(): Vec2 { | |
| 14 | const len = this.length() | |
| 15 | return len > 0 ? this.scale(1 / len) : Vec2.ZERO | |
| 16 | } | |
| 17 | ||
| 18 | limit(max: number): Vec2 { | |
| 19 | const len = this.length() | |
| 20 | return len > max ? this.scale(max / len) : this | |
| 21 | } | |
| 22 | ||
| 23 | lerp(v: Vec2, t: number): Vec2 { | |
| 24 | return new Vec2(this.x + (v.x - this.x) * t, this.y + (v.y - this.y) * t) | |
| 25 | } | |
| 26 | ||
| 27 | distanceTo(v: Vec2): number { return this.sub(v).length() } | |
| 28 | distanceSqTo(v: Vec2): number { return this.sub(v).lengthSq() } | |
| 29 | ||
| 30 | static readonly ZERO = new Vec2(0, 0) | |
| 31 | } |