-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvector.js
97 lines (97 loc) · 3 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
class Vector {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
length() {
return Math.sqrt(this.x ** 2 + this.y ** 2);
}
add(v) {
if (arguments.length !== 1) console.warn("Wrong number or arguments");
let x = this.x + v.x;
let y = this.y + v.y;
return new Vector(x, y);
}
addMut(v) {
if (arguments.length !== 1) console.warn("Wrong number or arguments");
this.x += v.x;
this.y += v.y;
return this;
}
sub(v) {
if (arguments.length !== 1) console.warn("Wrong number or arguments");
return this.add(v.scale(-1));
}
mult(v) {
if (arguments.length !== 1) console.warn("Wrong number or arguments");
return new Vector(this.x * v.x, this.y * v.y);
}
dist(v) {
if (arguments.length !== 1) console.warn("Wrong number or arguments");
const dx = this.x - v.x;
const dy = this.y - v.y;
return Math.sqrt(dx ** 2 + dy ** 2);
}
angleTo(v) {
if (arguments.length !== 1) console.warn("Wrong number or arguments");
const dx = v.x - this.x;
const dy = v.y - this.y;
return Math.atan2(-dy, dx);
}
scale(f) {
if (arguments.length !== 1) console.warn("Wrong number or arguments");
return new Vector(this.x * f, this.y * f);
}
scaleMut(f) {
if (arguments.length !== 1) console.warn("Wrong number or arguments");
this.x *= f;
this.y *= f;
return this;
}
copy() {
return new Vector(this.x, this.y);
}
set(x, y) {
if (arguments.length !== 2) console.warn("Wrong number or arguments");
this.x = x;
this.y = y;
return this;
}
setFrom(v) {
if (arguments.length !== 1) console.warn("Wrong number or arguments");
this.x = v.x;
this.y = v.y;
return this;
}
clamp(length) {
if (arguments.length !== 1) console.warn("Wrong number or arguments");
if (this.length() < length) return this;
const angle = Math.atan2(this.y, this.x);
return new Vector(Math.cos(angle) * length, Math.sin(angle) * length);
}
clampMut(length) {
if (arguments.length !== 1) console.warn("Wrong number or arguments");
if (this.length() < length) return this;
const angle = Math.atan2(this.y, this.x);
this.x = Math.cos(angle) * length;
this.y = Math.sin(angle) * length;
return this;
}
swap() {
return new Vector(this.y, this.x);
}
static fromAngle(a) {
if (arguments.length !== 1) console.warn("Wrong number or arguments");
return new Vector(Math.cos(a), -Math.sin(a));
}
drawFrom(v) {
if (arguments.length !== 1) console.warn("Wrong number or arguments");
ctx.save();
ctx.beginPath();
ctx.moveTo(v.x, v.y);
ctx.lineTo(v.x + this.x, v.y + this.y);
ctx.strokeStyle = "black";
ctx.stroke();
ctx.restore();
}
}