Skip to content

Instantly share code, notes, and snippets.

@HakurouKen
Created August 4, 2016 03:01
Show Gist options
  • Save HakurouKen/806589e92c8ed82ccda9915fbd59af0f to your computer and use it in GitHub Desktop.
Save HakurouKen/806589e92c8ed82ccda9915fbd59af0f to your computer and use it in GitHub Desktop.
A 2-dimensional vector in javascript.
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof module === 'object' && module.exports) {
module.exports = factory();
} else {
root.Vector2 = factory();
}
}(this, function () {
function Vector2(x,y){
this.x = x || 0;
this.y = y || 0;
}
function isVector(v){
return v instanceof Vector2;
}
function isVectorLike(v){
return v && v.x !== undefined && v.y !== undefined;
}
function args2Vector(args){
var arg0 = args[0];
if ( isVector(arg0) ) {
return arg0;
} else if ( arg0 && isVectorLike(arg0) ){
return new Vector2(arg0.x,arg0.y);
} else {
return new Vector2(arg0,args[1]);
}
}
function args2VectorLike(args){
var arg0 = args[0];
if ( isVectorLike(arg0) ) {
return arg0;
} else {
// return new Vector2(arg0,args[1]);
return {
x: +arg0 || 0,
y: +arg[1] || 0
}
}
}
Vector2.prototype = {
constructor: Vector2,
init: function(){
return args2Vector(arguments);
},
square: function() {
return this.x * this.x + this.y * this.y;
},
length: function() {
return Math.sqrt(this.square());
},
add: function() {
var v = args2VectorLike(arguments);
this.x += v.x;
this.y += v.y;
return this;
},
minus: function() {
var v = args2VectorLike(arguments);
this.x -= v.x;
this.y -= v.y;
return this;
},
multipy: function(scale) {
if( isVectorLike(scale) ){
this.x *= scale.x;
this.y *= scale.y;
} else {
this.x *= scale;
this.y *= scale;
}
return this;
},
divide: function(scale) {
return this.multipy(1/scale);
},
unit: function(){
return this.divide(this.length());
},
negative: function(){
return this.multipy(-1);
},
clone: function(){
return new Vector2(this.x,this.y);
},
toArray: function(){
return [this.x,this.y];
}
};
Vector2.fromPoints = function(p1, p2) {
return new Vector2(p2.x - p1.x, p2.y - p1.y);
};
Vector2.fromCoordinate = function(x,y) {
return new Vector2(x,y);
};
Vector2.fromArray = function(arr){
return new Vector2(arr[0],arr[1]);
};
Vector2.isVector = isVector;
Vector2.isVectorLike = isVectorLike;
return Vector2;
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment