Skip to content

Commit 31fa033

Browse files
committed
feat: add new functions to vector
dot, cross, toAngles, angleTo, toArray, clone
1 parent bdacb1e commit 31fa033

File tree

1 file changed

+52
-3
lines changed

1 file changed

+52
-3
lines changed

src/vector.js

Lines changed: 52 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,6 @@ function innerCalc(alg, result) {
3838
}
3939
}
4040

41-
function square(val) { return val * val; }
42-
4341
export class Vector {
4442
constructor(x, y, z) {
4543
if (typeof x === 'function') {
@@ -64,12 +62,63 @@ export class Vector {
6462
return this.normalize();
6563
}
6664

65+
// methods ispired by
66+
// https://evanw.github.io/lightgl.js/docs/vector.html
67+
68+
dot(v) {
69+
return this.x * v.x + this.y * v.y + this.z * v.z;
70+
}
71+
72+
cross(v) {
73+
return new Vector(
74+
this.y * v.z - this.z * v.y,
75+
this.z * v.x - this.x * v.z,
76+
this.x * v.y - this.y * v.x
77+
);
78+
}
79+
80+
crossNormalize(v) {
81+
const vec = this.cross(v);
82+
const { length } = vec;
83+
vec.x /= length;
84+
vec.y /= length;
85+
vec.z /= length;
86+
return vec;
87+
}
88+
89+
cn(v) {
90+
return this.crossNormalize(v);
91+
}
92+
93+
toAngles() {
94+
return {
95+
theta: Math.atan2(this.z, this.x),
96+
phi: Math.asin(this.y / this.length)
97+
};
98+
}
99+
100+
angleTo(a) {
101+
return Math.acos(this.dot(a) / (this.length * a.length));
102+
}
103+
104+
toArray() {
105+
return [this.x, this.y, this.z];
106+
}
107+
108+
clone() {
109+
return new Vector(this.x, this.y, this.z);
110+
}
111+
112+
equals(v) {
113+
return this.x === v.x && this.y === v.y && this.z === v.z;
114+
}
115+
67116
toString() {
68117
return `[${this.x}, ${this.y}, ${this.z}]`;
69118
}
70119

71120
get length() {
72-
return Math.sqrt(square(this.x) + square(this.y) + square(this.z));
121+
return Math.sqrt(this.dot(this));
73122
}
74123

75124
get len() {

0 commit comments

Comments
 (0)