-
Notifications
You must be signed in to change notification settings - Fork 0
/
vec.js
109 lines (97 loc) · 2.2 KB
/
vec.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
98
99
100
101
102
103
104
105
106
107
108
109
/**
* Alternate vec implementation for the physics
This one uses the approach of C += vs + operators
*/
var CVec = function(x, y) {
this.type = 'CVector';
this.x = x ? x : 0;
this.y = y ? y : 0;
}
CVec.prototype.set = function(other) {
this.x = other.x;
this.y = other.y;
return this;
}
CVec.prototype.isub = function(other) {
this.x -= other.x;
this.y -= other.y;
return this;
}
CVec.prototype.sub = function(other) {
return new CVec(
this.x - other.x,
this.y - other.y
);
}
CVec.prototype.iadd = function(other) {
this.x += other.x;
this.y += other.y;
return this;
}
CVec.prototype.add = function(other) {
return new CVec(
this.x + other.x,
this.y + other.y
);
}
CVec.prototype.imul = function(scalar) {
this.x *= scalar;
this.y *= scalar;
return this;
}
CVec.prototype.mul = function(scalar) {
return new CVec(
this.x * scalar,
this.y * scalar
)
}
CVec.prototype.idiv = function(scalar) {
this.x /= scalar;
this.y /= scalar;
return this;
}
CVec.prototype.div = function(scalar) {
return new CVec(
this.x / scalar,
this.y / scalar
)
}
CVec.prototype.inverted = function() {
return new CVec(-this.x, -this.y);
}
CVec.prototype.normalized = function() {
var x = this.x, y = this.y;
var length = this.length();
return new CVec(x/length, y/length);
}
CVec.prototype.normalize = function() {
var x=this.x, y=this.y;
var length = this.length();
this.x = x/length;
this.y = y/length;
return this;
}
CVec.prototype.length = function() {
return Math.sqrt(this.x*this.x + this.y*this.y);
}
CVec.prototype.lengthSq = function() {
return this.x*this.x + this.y*this.y;
}
CVec.prototype.distance = function(other) {
var x = this.x - other.x;
var y = this.y - other.y;
return Math.sqrt(x*x + y*y);
}
CVec.prototype.distanceSq = function(other) {
var x = this.x - other.x;
var y = this.y - other.y;
return x*x + y*y;
}
CVec.prototype.dot = function(other) {
var x = this.x * other.x;
var y = this.y * other.y;
return x + y;
}
CVec.prototype.copy = function() {
return new CVec(this.x, this.y);
}