Skip to content

Instantly share code, notes, and snippets.

@tamask
Created December 7, 2012 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tamask/4234569 to your computer and use it in GitHub Desktop.
Save tamask/4234569 to your computer and use it in GitHub Desktop.
Vector2
Vector2.prototype = {
init: function(x, y) {
this.x = x;
this.y = y;
},
copy: function() {
return new Vector2(this.x, this.y);
},
add: function(o) {
this.x += o.x;
this.y += o.y;
return this;
},
subtract: function(o) {
this.x -= o.x;
this.y -= o.y;
return this;
},
multiply: function(o) {
this.x *= o;
this.y *= o;
return this;
},
divide: function(o) {
this.x /= o;
this.y /= o;
},
dot: function(o) {
return this.x * o.x + this.y * o.y;
},
cross: function(o) {
var x = this.x;
var y = this.y;
this.x = y;
this.y = -x;
return this;
},
magnitude: function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
},
magnitude_squared: function() {
return this.x * this.x + this.y * this.y;
},
normalize: function() {
var d = this.magnitude();
if (d) {
this.x /= d;
this.y /= d;
}
return this;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment