-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVector2.js
More file actions
81 lines (64 loc) · 1.57 KB
/
Vector2.js
File metadata and controls
81 lines (64 loc) · 1.57 KB
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
/**
* Vector2.js
* A 2D vector class with an x and y component
*/
class Vector2{
constructor(_x, _y){
this.x = _x;
this.y = _y;
}
// Add the given x and y values to the vector
Add(_x, _y) {
this.x += _x;
this.y += _y;
}
// Add the given vector to this vector (multiplied by the given multiplier if given)
Add(_vector, multiplier = 1) {
this.x += _vector.GetX() * multiplier;
this.y += _vector.GetY() * multiplier;
}
// Rotate the vector by the given angle in degrees
Rotate(_angle) {
// Store sin and cos values in degrees
var cos = Math.cos(_angle * Math.PI / 180);
var sin = Math.sin(_angle * Math.PI / 180);
// Store the current vector values
var tempX = this.x;
var tempY = this.y;
// Rotate the vector
this.x = tempX * cos - tempY * sin;
this.y = tempX * sin + tempY * cos;
}
//
// Static Methods
//
// Returns a random vector with a magnitude of 1
static Random() {
var newVector = new Vector2(0, 1);
newVector.Rotate(Math.random() * 360);
return newVector;
}
//
// Basic Getters and Setters
//
// Get the angle of the vector in degrees
GetAngle() {
return Math.atan2(this.y, this.x) * 180 / Math.PI;
}
GetX() {
return this.x;
}
GetY() {
return this.y;
}
SetX(_x) {
this.x = _x;
}
SetY(_y) {
this.y = _y;
}
Set(_x, _y) {
this.x = _x;
this.y = _y;
}
}