-
Notifications
You must be signed in to change notification settings - Fork 0
/
vec2.js
97 lines (79 loc) · 1.36 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// 2次元のベクトル計算。
class Vec2 {
constructor(x, y) {
this.x = x
this.y = y
}
set(x, y) {
this.x = x
this.y = y
return this
}
copy(v) {
this.x = v.x
this.y = v.y
return this
}
clone() {
return new Vec2(this.x, this.y)
}
add(v) {
this.x += v.x
this.y += v.y
return this
}
sub(v) {
this.x -= v.x
this.y -= v.y
return this
}
mul(r) {
this.x *= r
this.y *= r
return this
}
dot(v) {
return this.x * v.x + this.y * v.y
}
cross(v) {
return this.x * v.y - this.y * v.x
}
length() {
return Math.sqrt(this.x * this.x + this.y * this.y)
}
lengthSq() {
return this.x * this.x + this.y * this.y
}
normalize() {
var length = 1 / Math.sqrt(this.x * this.x + this.y * this.y)
this.x *= length
this.y *= length
return this
}
neg() {
this.x = -this.x
this.y = -this.y
return this
}
perpendicular() {
var temp = this.x
this.x = -this.y
this.y = temp
return this
}
static add(a, b) {
return new Vec2(a.x + b.x, a.y + b.y)
}
static sub(a, b) {
return new Vec2(a.x - b.x, a.y - b.y)
}
static sub(a, b) {
return new Vec2(a.x - b.x, a.y - b.y)
}
static mul(v, r) {
return new Vec2(v.x * r, v.y * r)
}
static perpendicular(v) {
return new Vec2(-v.y, v.x)
}
}