-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvector.js
76 lines (76 loc) · 1.75 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
class Vector {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
length() {
return Math.sqrt(this.x ** 2 + this.y ** 2);
}
clamp(length) {
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 (this.length() > length) {
const angle = Math.atan2(this.y, this.x);
this.set(Math.cos(angle) * length, Math.sin(angle) * length);
}
return this;
}
add(v) {
let x = this.x + v.x;
let y = this.y + v.y;
return new Vector(x, y);
}
addMut(v) {
this.x += v.x;
this.y += v.y;
return this;
}
sub(v) {
return this.add(v.scale(-1));
}
dist(v) {
const dx = this.x - v.x;
const dy = this.y - v.y;
return Math.sqrt(dx ** 2 + dy ** 2);
}
angleTo(v) {
const dx = v.x - this.x;
const dy = v.y - this.y;
return Math.atan2(dy, dx);
}
scale(f) {
return new Vector(this.x * f, this.y * f);
}
scaleMut(f) {
this.x *= f;
this.y *= f;
return this;
}
copy() {
return new Vector(this.x, this.y);
}
set(x, y) {
this.x = x;
this.y = y;
return this;
}
setFrom(v) {
this.x = v.x;
this.y = v.y;
}
static fromAngle(a) {
return new Vector(Math.cos(a), Math.sin(a));
}
draw(v) {
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();
}
}