-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.ts
53 lines (43 loc) · 997 Bytes
/
vector.ts
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
export default class Vector {
x: number
y: number
constructor (x: number = .0, y: number = .0) {
this.x = x
this.y = y
}
clone (): Vector {
return new Vector(this.x, this.y)
}
size (): number {
return Math.sqrt(this.x * this.x + this.y * this.y)
}
add (v: Vector): Vector {
return new Vector(this.x + v.x, this.y + v.y)
}
sub (v: Vector): Vector {
return new Vector(this.x - v.x, this.y - v.y)
}
mul (r: number): Vector {
return new Vector(this.x * r, this.y * r)
}
div (r: number): Vector {
return new Vector(this.x / r, this.y / r)
}
normalize (): Vector {
return this.div(this.size())
}
rotate (rad: number): Vector {
const c = Math.cos(rad)
const s = Math.sin(rad)
return new Vector(
this.x * c - this.y * s,
this.x * s + this.y * c
)
}
lerp (v: Vector, r: number): Vector {
return new Vector(
this.x * (1 - r) + v.x * r,
this.y * (1 - r) + v.y * r
)
}
}