-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVector.js
66 lines (53 loc) · 1.27 KB
/
Vector.js
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
export default class Vector {
constructor(x = 0, y = 0) {
this.mat = math.matrix([x, y])
}
x(set) {
return set ? this.mat.set([0], set) : this.mat.get([0])
}
y(set) {
return set ? this.mat.set([1], set) : this.mat.get([1])
}
clone() {
return new Vector(this.mat.get([0]), this.mat.get([1]))
}
add(v) {
this.mat = math.add(this.mat, v.mat)
return this
}
sub(v) {
this.mat = math.subtract(this.mat, v.mat)
return this
}
scale(v) {
this.mat = math.multiply(this.mat, typeof v === 'number' ? v : v.mat)
return this
}
magnitude() {
return math.norm(this.mat)
}
setMagnitude(mag) {
this.scale(mag / math.norm(this.mat))
return this
}
normalize() {
this.setMagnitude(1)
return this
}
invert() {
this.scale(-1)
return this
}
projectOn(v) {
let unitVector = v.clone().normalize()
let scalarProjection = math.dot(this.mat, unitVector.mat)
return unitVector.setMagnitude(scalarProjection)
}
distance(v) {
return math.distance(this.mat, v.mat)
}
zero() {
this.mat = math.matrix([0, 0])
return this
}
}