-
Notifications
You must be signed in to change notification settings - Fork 0
/
vec2.js
77 lines (59 loc) · 1.69 KB
/
vec2.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
export default class Vec2 {
constructor(x, y) {
this.x = x;
this.y = y;
}
angle() {
let x = Math.abs(this.x);
let y = Math.abs(this.y);
let a = Math.atan(y / x);
if (this.x < 0) a = Math.PI - a;
if (this.y < 0) a = 2*Math.PI - a;
return a;
}
dot(v) {
return this.x*v.x + this.y*v.y;
}
len() {
return Math.sqrt(this.x*this.x + this.y*this.y);
}
rot(theta) {
const rmat = [[Math.cos(theta), -Math.sin(theta)],
[Math.sin(theta), Math.cos(theta)]];
return new Vec2(this.x*rmat[0][0] + this.y*rmat[0][1],
this.x*rmat[1][0] + this.y*rmat[1][1]);
}
rot_towards(v, frac) {
const target_angle = v.angle();
if (!isNaN(target_angle)) {
let angle_diff = target_angle - this.angle();
if (angle_diff > Math.PI) angle_diff = 2*Math.PI - angle_diff;
if (angle_diff < -Math.PI) angle_diff = 2*Math.PI + angle_diff;
return this.rot(angle_diff * frac);
} else {
return new Vec2(this.x, this.y);
}
}
add(v) {
return new Vec2(this.x + v.x, this.y + v.y);
}
sub(v) {
return new Vec2(this.x - v.x, this.y - v.y);
}
smul(s) {
return new Vec2(this.x*s, this.y*s);
}
norm() {
const l = this.len();
return l == 0 ? new Vec2(0,0) : new Vec2(this.x / l, this.y / l);
}
dist_to(v) {
return this.sub(v).len();
}
unit_to(v) {
return v.sub(this).norm();
}
toString() {
return `{x: ${this.x}, y: ${this.y}}`;
}
}