-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvector.js
85 lines (76 loc) · 1.53 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
/**
* 用于矢量计算的类
*/
class Vector {
/**
* 构造函数
* @param x 横坐标
* @param y 纵坐标
*/
constructor(x, y) {
this.x = x || 0;
this.y = y || 0;
}
/**
* 矢量加
* @param vector
* @returns {Vector}
*/
add(vector) {
return new Vector(this.x + vector.x, this.y + vector.y);
}
/**
* 矢量减
* @param vector
* @returns {Vector}
*/
subtract(vector) {
return new Vector(this.x - vector.x, this.y - vector.y);
}
/**
* 矢量乘
* @param vector
* @returns {Vector}
*/
multiply(vector) {
return new Vector(this.x * vector.x, this.y * vector.y);
}
/**
* 矢量乘以标量
* @param scalar
* @returns {Vector}
*/
multiplyScalar(scalar) {
return new Vector(this.x * scalar, this.y * scalar);
}
/**
* 矢量除
* @param vector
* @returns {Vector}
*/
divide(vector) {
return new Vector(this.x / vector.x, this.y / vector.y);
}
/**
* 矢量除以标量
* @param scalar
* @returns {Vector}
*/
divideScalar(scalar) {
return new Vector(this.x / scalar, this.y / scalar);
}
/**
* 矢量长度
* @returns {number}
*/
length() {
return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2));
}
/**
* 矢量标准化
* @returns {Vector}
*/
normalize() {
return this.divideScalar(this.length());
}
}