-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvector2D.js
More file actions
85 lines (69 loc) · 2.06 KB
/
vector2D.js
File metadata and controls
85 lines (69 loc) · 2.06 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
82
83
84
85
define([], function(){
//This is a subset of vector3D.js
//see vector3D.js for information about each function
function Vector2D(a, b){
this.vectorArray = new Float32Array(2);
this.vectorArray[0] = a;
this.vectorArray[1] = b;
}
Vector2D.prototype.getVectorAsArray = function(){
return this.vectorArray;
};
Vector2D.prototype.set = function(a, b){ //Completely overrides current this.vectorArray
this.vectorArray = new Float32Array(2);
this.vectorArray[0] = a;
this.vectorArray[1] = b;
};
Vector2D.prototype.setAt = function(i, a){
this.vectorArray[i] = a;
};
Vector2D.prototype.at = function(i){
return this.vectorArray[i];
};
Vector2D.prototype.getLength = function(){
return 2;
};
Vector2D.prototype.dot = function(v){
var a = this.vectorArray;
var b = v.vectorArray;
var result = a[0] * b[0] + a[1] * b[1];
return result;
};
Vector2D.prototype.magnitude = function(){
var a = this.vectorArray;
var k = a[0] * a[0] + a[1] * a[1];
return Math.sqrt(k);
};
Vector2D.prototype.add = function(v){
var a = this.vectorArray;
var b = v.vectorArray;
var result = new Vector2D(a[0] + b[0], a[1] + b[1]);
return result;
};
Vector2D.prototype.subtract = function(v){
var a = this.vectorArray;
var b = v.vectorArray;
var result = new Vector2D(a[0] - b[0], a[1] - b[1]);
return result;
};
Vector2D.prototype.multiply = function(x){ //scalar multiplication
var a = this.vectorArray;
var result = new Vector2D(a[0] * x, a[1] * x);
return result;
};
Vector2D.prototype.unit = function(){
if (typeof this.unitVector === "undefined") {
this.unitVector = this.multiply(1 / this.magnitude());
}
return this.unitVector;
};
Vector2D.prototype.angle = function(v){ //angle between two vectors
var angle = Math.acos(this.dot(v) / (this.magnitude() * v.magnitude()));
return angle;
};
Vector2D.prototype.area = function(v){ //area of the parallelogram formed by two vectors
var a = this.vectorArray[0] * v.vectorArray[1] - this.vectorArray[1] * v.vectorArray[0];
return a;
};
return Vector2D;
});