Last active
January 12, 2017 17:57
-
-
Save simondell/26cac4f84a1139db4094918745d50cfc to your computer and use it in GitHub Desktop.
A very simple 2d vector implementation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Vector2D (x, y) { | |
this.x = x || 0; | |
this.y = y || 0; | |
} | |
Vector2D.prototype = { | |
constructor: Vector2D, | |
set: function set (arg1, y) { | |
if( arg1 instanceof Vector2D ) { | |
this.x = arg1.x; | |
this.y = arg1.y; | |
} else { | |
if( typeof arg1 !== 'number' || typeof y !== 'number' ) { | |
throw 'Must supply eithr a Vector2D or two numbers'; | |
} | |
this.x = arg1 || 0; | |
this.y = y || 0; | |
} | |
}, | |
add: function add (v2) { | |
this.x += v2.x; | |
this.y += v2.y; | |
}, | |
sub: function sub (v2) { | |
this.x -= v2.x; | |
this.y -= v2.y; | |
}, | |
mult: function mult (scale) { | |
this.x *= scale; | |
this.y *= scale; | |
}, | |
div: function div (factor) { | |
if( factor === 0 ) throw 'Division by zero causes problems. Don\'t do it.'; | |
this.x /= factor; | |
this.y /= factor; | |
} | |
} | |
Vector2D.sum = function sum (v1, v2) { | |
return new Vector2D( | |
v1.x + v2.x, | |
v1.y + v2.y | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment