Laya向量及数学
前几天需要用到向量的时候,发现Laya的2D向量封装在3D里,要想使用,还需要引用3D库,所以参照Laya的库,自己封装了一个2D向量
export class Vector2D {
x: number;
y: number;
static zero = new Vector2D(0, 0)
static one = new Vector2D(1, 1)
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
/**
* 模长
*/
norm() {
if (!this.x && !this.y) return
return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2))
}
/**
* Vector加法
* @param Vector Vector2D对象
*/
VectorSum(Vector: Vector2D): Vector2D {
return new Vector2D(this.x + Vector.x, this.y + Vector.y);;
}
/**
* 点积
*
* 若点积大于0,则相近,小于0,则相反。
*
* 点积为0,夹角为90度。
*
* 点积小于0,夹角超过90度。
*
* 点积大于0,夹角小于90度。
*
* @param VectorA 归一化后Vector
* @param VectorB 归一化后Vector
*/
static dotProduct(VectorA: Vector2D, VectorB: Vector2D) {
return (VectorA.x * VectorB.x) + (VectorA.y * VectorB.y);
}
/**
* 归一化,归一化后模长为1
*/
normalize(): Vector2D {
if (!this.x && !this.y) return
return new Vector2D(this.x * Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)), this.y * Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)))
}
}
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
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
上次更新: 2020/11/03, 06:57:50