-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.js
97 lines (87 loc) · 2.18 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 {
/**
* Creates a new vector using cartesian coordinates.
* @param {number} [x=0]
* @param {number} [y=0]
*/
constructor(x = 0, y = 0) {
this.x = x
this.y = y
}
/**
* Creates a Vector with length r and angle theta.
* @param {number} r - the length
* @param {number} theta - the angle(in radians)
* @returns {Vector}
*/
static fromPolar(r, theta) {
return new Vector(r * Math.cos(theta), r * Math.sin(theta))
}
/**
* Returns a copy of the Vector.
* @return {Vector}
*/
copy() {
return new Vector(this.x, this.y)
}
/**
* Returns the angle of the Vector(in radians).
* @returns {number}
*/
get angle() {
return Math.atan2(this.y, this.x)
}
/**
* Returns the length of the Vector squared.
* @returns {number}
*/
get length2() {
return this.dot(this)
}
/**
* Returns the length of the Vector.
* @returns {number}
*/
get length() {
return Math.sqrt(this.length2)
}
/**
* Returns a new Vector scaled by s.
* @param {number} s - the scale factor
* @returns {Vector}
*/
scale(s) {
return new Vector(this.x * s, this.y * s)
}
/**
* Returns a new Vector that is sum of other and this.
* @param {Vector} other - the Vector to add
* @returns {Vector}
*/
add(other) {
return new Vector(this.x + other.x, this.y + other.y)
}
/**
* Returns a new Vector that the difference between this and other.
* @param {Vector} other - the Vector to be subtracted(minuend)
* @returns {Vector}
*/
sub(other) {
return new Vector(this.x - other.x, this.y - other.y)
}
/**
* Returns a new Vector that is the negative of this.
* @returns {Vector}
*/
neg() {
return new Vector(-this.x, -this.y)
}
/**
* Returns the dot product of this with the Vector other.
* @param {Vector} other - the Vector to calculate the dot product with.
* @returns {number}
*/
dot(other) {
return this.x * other.x + this.y * other.y
}
}