Vector JS
by Sam Fereday
JavaScript
var vector = {
_x: 1,
_y: 0,
//
create: function(x, y) {
var obj = Object.create(this);
obj.setX(x);
obj.setY(y);
return obj;
},
// Starts of as a unit vector, this is a vector with a length of 1.
setX: function(n){
this._x = n;
},
setY: function(n){
this._y = n;
},
//
getX: function(){
return this._x;
},
getY: function(){
return this._y;
},
getAll: function(){
return this._x + " : " + this._y;
},
//
setAngle: function(angle){
var length = this.getLength();
this._x = Math.cos(angle) * length;
this._y = Math.sin(angle) * length;
},
getAngle: function(){
return Math.atan2(this._y, this._x);
},
setLength: function(length) {
var angle = this.getAngle();
this._x = Math.cos(angle) * length;
this._y = Math.sin(angle) * length;
},
getLength: function(){
return Math.sqrt(this._x * this._x + this._y * this._y);
},
//
add: function(v2) {
return vector.create(this._x + v2.getX(), this._y + v2.getY());
},
subtract: function(v2) {
return vector.create(this._x - v2.getX(), this._y - v2.getY());
},
multiply: function(val){
return vector.create(this._x * val, this._y * val);
},
divide: function(val){
return vector.create(this._x / val, this._y / val);
},
//
addTo: function(v2) {
this._x += v2.getX();
this._y += v2.getY();
},
subtractTo: function(v2) {
this._x -= v2.getX();
this._y -= v2.getY();
},
multiplyTo: function(val) {
this._x *= val;
this._y *= val;
},
divideTo: function(val) {
this._x /= val;
this._y /= val;
}
}
// Do some stuff with it.
var v1 = vector.create(10, 5);
var v2 = vector.create(3, 4);
var v3 = v1.multiply();
console.log(v3.getAll());