fuzzyworld

bubbles / files / src / physics / Vector2.ts

Vector2.ts

Blame: the commit that last changed each line · file · history

dcc4757f 2026-04-09 Pavel Safronov1export class Vector2 {
2 constructor(public x: number, public y: number) { }
3
4 static zero(): Vector2 {
5 return new Vector2(0, 0);
6 }
7
8 static from(x: number, y: number): Vector2 {
9 return new Vector2(x, y);
10 }
11
12 add(v: Vector2): Vector2 {
13 return new Vector2(this.x + v.x, this.y + v.y);
14 }
15
16 sub(v: Vector2): Vector2 {
17 return new Vector2(this.x - v.x, this.y - v.y);
18 }
19
20 scale(s: number): Vector2 {
21 return new Vector2(this.x * s, this.y * s);
22 }
23
24 dot(v: Vector2): number {
25 return this.x * v.x + this.y * v.y;
26 }
27
28 magnitude(): number {
29 return Math.sqrt(this.x * this.x + this.y * this.y);
30 }
31
32 normalize(): Vector2 {
33 const m = this.magnitude();
34 if (m === 0) return Vector2.zero();
35 return this.scale(1 / m);
36 }
37
38 clone(): Vector2 {
39 return new Vector2(this.x, this.y);
40 }
41
42 addMut(v: Vector2): this {
43 this.x += v.x;
44 this.y += v.y;
45 return this;
46 }
47
48 scaleMut(s: number): this {
49 this.x *= s;
50 this.y *= s;
51 return this;
52 }
53}