Skip to content

Instantly share code, notes, and snippets.

@alejandrolechuga
Created January 14, 2012 04:09
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 alejandrolechuga/1610238 to your computer and use it in GitHub Desktop.
Save alejandrolechuga/1610238 to your computer and use it in GitHub Desktop.
Vector2d
/**
* Running tests
* Create Vectors two-dimensional
*/
var v1 = new Vector2d(1,2);
var v2 = new Vector2d(3,4);
/**
* Vector.getX
* Vector.setX
*/
console.log(v1.getX());
v1.setX(1);
console.log(v1.getX());
/**
* Vector.getY
* Vector.setY
*/
console.log(v2.getX());
v2.setX(3);
console.log(v2.getX());
/**
* Vector.scale
* Vector.toString
*/
v1.scale(2);
console.log(v1.toString());
/**
* Vector.add
*/
v1.add(v2);
console.log(v1.toString());
/**
* Vector.sub
*/
v1.sub(v2);
console.log(v1.toString());
/**
* Vector.negate
*/
v1.negate();
console.log(v1.toString());
/**
* Vector.length
*/
console.log(v1.length());
/**
* Vector.lengthSquared
*/
console.log(v1.lengthSquared());
/**
* Vector.normalize
*/
console.log(v1.normalize());
/**
* Vector.rotate
*/
v1.rotate(Math.PI * 0.5);
console.log(v1.toString());
var Vector2d = function () {
this.x = arguments[0] || 0;
this.y = arguments[1] || 0;
/**
* @method: setX
* @param: int
*/
this.setX = function (x) {
this.x = x;
};
/**
* @method: setY
* @param: int
*/
this.setY = function (y) {
this.y = y;
};
/**
* @method: getX
*/
this.getX = function () {
return this.x;
};
/**
* @method: getY
*/
this.getY = function () {
return this.y;
}
/**
* @method: scale
*/
this.scale = function (s) {
this.x *= s;
this.y *= s;
};
/**
* @method: add
* @param: Vector
*/
this.add = function (vector) {
this.x += vector.x;
this.y += vector.y;
};
/**
* @method: sub
* @param: Vector
*/
this.sub = function (vector) {
this.x -= vector.x;
this.y -= vector.y;
};
/**
* @method: negate
*/
this.negate = function () {
this.x = -this.x;
this.y = -this.y;
};
/**
* @method: length
*/
this.length = function (){
return Math.sqrt(this.x * this.x + this.y * this.y);
};
/**
* @method: lengthSquared
*/
this.lengthSquared = function () {
return this.x * this.x + this.y * this.y;
};
/**
* @method: normalize
*/
this.normalize = function () {
var len = this.length();
if (len) {
this.x /= len;
this.y /= len;
}
return len;
};
/**
* @method: rotate
* @param: int
*/
this.rotate = function (angle) {
var x = this.x,
y = this.y,
cosVal = Math.cos(angle),
sinVal = Math.sin(angle);
this.x = this.x * cosVal - this.y * sinVal;
this.y = this.x * sinVal + this.y * cosVal;
};
/**
* @method: rotate
*/
this.toString = function () {
return "(" + this.getX() + "," + this.getY() + ")";
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment