-
Notifications
You must be signed in to change notification settings - Fork 0
/
Vector.js
127 lines (107 loc) · 2.79 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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
// Mostly based from https://github.com/processing/p5.js/blob/master/src/math/p5.Vector.js
class Vector {
constructor(pos = {}) {
let { x, y, z } = pos;
this.value = { x: x || 0, y: y || 0, z: z || 0 };
return this;
}
set(vector) {
let v = {};
if (vector.value) v = vector.value;
else v = vector;
this.value.x = v.x || this.value.x;
this.value.y = v.y || this.value.y;
this.value.z = v.z || this.value.z;
return this;
}
add(vector) {
let v = {};
if (vector.value) v = vector.value;
else v = vector;
this.value.x += v.x || 0;
this.value.y += v.y || 0;
this.value.z += v.z || 0;
return this;
}
sub(vector) {
let v = {};
if (vector.value) v = vector.value;
else v = vector;
this.value.x -= v.x || 0;
this.value.y -= v.y || 0;
this.value.z -= v.z || 0;
return this;
}
copy(v = this) {
return new Vector({ ...v.value });
}
mag() {
const x = this.value.x,
y = this.value.y,
z = this.value.z;
const magSq = x * x + y * y + z * z;
return Math.sqrt(magSq);
};
dist(v) {
if (v.value) {
return v
.copy()
.sub(this)
.mag();
}
else {
return new Vector(v).sub(this).mag();
}
}
diff(v) {
return this.copy().sub(v);
}
limit(max) {
const mSq = this.magSq();
if (mSq > max * max) {
this.div(this, Math.sqrt(mSq)) //normalize it
.mult(max);
}
return this;
};
magSq() {
const x = this.value.x;
const y = this.value.y;
const z = this.value.z;
return x * x + y * y + z * z;
};
setMag(n) {
return this.normalize().mult(n);
}
normalize() {
const len = this.mag();
// here we multiply by the reciprocal instead of calling 'div()'
// since div duplicates this zero check.
if (len !== 0) this.mult(1 / len);
return this;
};
mag(vecT = this) {
const x = vecT.value.x,
y = vecT.value.y,
z = vecT.value.z;
const magSq = x * x + y * y + z * z;
return Math.sqrt(magSq);
};
mult(x, y, z) {
if (arguments.length === 1) {
this.value.x *= x;
this.value.y *= x;
this.value.z *= x;
}
if (arguments.length === 2) {
this.value.x *= x;
this.value.y *= y;
}
if (arguments.length === 3) {
this.value.x *= x;
this.value.y *= y;
this.value.z *= z;
}
return this;
};
}