-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvector.js
More file actions
70 lines (57 loc) · 1.15 KB
/
vector.js
File metadata and controls
70 lines (57 loc) · 1.15 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
function Vector(x, y) {
this.x = x;
this.y = y;
this.add = function(v) {
this.x = this.x + v.x;
this.y = this.y + v.y;
};
this.sub = function(v) {
this.x = this.x - v.x;
this.y = this.y - v.y
};
this.mult = function(b) {
this.x = this.x * b;
this.y = this.y * b;
};
this.div = function(b) {
this.x = this.x / b;
this.y = this.y / b;
};
this.mag = function(b) {
return Math.sqrt(this.x * this.x + this.y * this.y);
};
this.normalize = function() {
var m = this.mag();
if(m != 0) {
this.div(m);
}
};
this.deepCopy = function() {
return new Vector(this.x, this.y);
}
Vector.random2D = function() {
var out = new Vector(random0to1(), random0to1());
out.normalize();
return out;
};
// v1 + v2
Vector.add = function(v1, v2) {
var v3 = new Vector(v1.x + v2.x, v1.y + v2.y);
return v3;
};
// v1 - v2
Vector.sub = function(v1, v2) {
var v3 = new Vector(v1.x - v2.x, v1.y - v2.y);
return v3;
};
// v1 * n
Vector.mult = function(v1, n) {
var v2 = new Vector(v1.x * n, v1.y * n);
return v2;
};
// v1 / n
Vector.div = function(v1, n) {
var v2 = new Vector(v1.x / n, v1.y / n);
return v2;
};
};