-
Notifications
You must be signed in to change notification settings - Fork 1
/
vec2.ts
98 lines (81 loc) · 2.42 KB
/
vec2.ts
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
namespace kodu {
export class Vec2 {
constructor(public x: number, public y: number) { }
public static Add(a: Vec2, b: Vec2): Vec2 {
return new Vec2(
a.x + b.x,
a.y + b.y
);
}
public static Sub(a: Vec2, b: Vec2): Vec2 {
return new Vec2(
a.x - b.x,
a.y - b.y
);
}
public static Mul(a: Vec2, b: Vec2): Vec2 {
return new Vec2(
a.x * b.x,
a.y * b.y
);
}
public static Sign(v: Vec2): Vec2 {
return new Vec2(
v.x < 0 ? -1 : 1,
v.y < 0 ? -1 : 1
);
}
public static Abs(v: Vec2): Vec2 {
return new Vec2(
Math.abs(v.x),
Math.abs(v.y)
);
}
public static Transpose(v: Vec2): Vec2 {
return new Vec2(v.y, v.x);
}
public static Neg(v: Vec2): Vec2 {
return new Vec2(-v.x, -v.y);
}
public static Normal(v: Vec2, mag?: number): Vec2 {
if (!mag) {
const magSq = (v.x * v.x + v.y * v.y);
if (magSq === 1) { return v; }
mag = Math.sqrt(magSq);
}
return new Vec2(
v.x / mag,
v.y / mag
);
}
public static Scale(v: Vec2, scalar: number): Vec2 {
return new Vec2(
v.x * scalar,
v.y * scalar
);
}
public static Magnitude(v: Vec2): number {
const magSq = (v.x * v.x + v.y * v.y);
return Math.sqrt(magSq);
}
public static MagnitudeSq(v: Vec2): number {
return (v.x * v.x + v.y * v.y);
}
public static Dot(a: Vec2, b: Vec2): number {
return a.x * b.x + a.y * b.y;
}
public static Determinant(a: Vec2, b: Vec2): number {
return a.x * b.y - a.y * b.x;
}
public static DistanceSq(a: Vec2, b: Vec2): number {
const d = Vec2.Sub(a, b);
return (d.x * d.x) + (d.y * d.y);
}
public static Distance(a: Vec2, b: Vec2): number {
return Math.sqrt(Vec2.DistanceSq(a, b));
}
}
export function mkVec2(x = 0, y = 0): Vec2 {
return new Vec2(x, y);
}
}