Complete vector class in JavaScript

This class is usefull for game programming or for math in JavaScript.

Enjoy.


var Vector = {
_x: 1,
_y: 0,

create: function(x, y) {
var obj = Object.create(this);
obj.setX(x);
obj.setY(y);
return obj;
},

setX: function(value) {
this._x = value;
},

getX: function() {
return this._x;
},

setY: function(value) {
this._y = value;
},

getY: function() {
return 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();
},

subtractFrom: function(v2) {
this._x -= v2.getX();
this._y -= v2.getY();
},

multiplyBy: function(val) {
this._x *= val;
this._y *= val;
},

divideBy: function(val) {
this._x /= val;
this._y /= val;
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s