function vector(x, y) { this.x = x; this.y = y; this.length = function() { return Math.sqrt((this.x * this.x) + (this.y * this.y)); } this.toAngle = function() { return (Math.atan2(this.y, this.x) * 180 / Math.PI) + 90; } this.normalize = function() { var newVector = this.getCopy(); if(newVector.length() != 0) { var length = newVector.length(); newVector.x /= length; newVector.y /= length; } return newVector; } this.lerpTo = function(otherVector, t) { var delta = otherVector.subtract(this); return this.add(delta.stretch(t)); } this.distanceTo = function(otherVector) { var dX = this.x - otherVector.x; var dY = this.y - otherVector.y; return new vector(dX, dY).length(); } this.add = function(otherVector) { var newVector = this.getCopy(); newVector.x += otherVector.x; newVector.y += otherVector.y; return newVector; } this.subtract = function(otherVector) { var newVector = this.getCopy(); newVector.x -= otherVector.x; newVector.y -= otherVector.y; return newVector; } this.multiply = function(otherVector) { var newVector = this.getCopy(); newVector.x *= otherVector.x; newVector.y *= otherVector.y; return newVector; } this.divide = function(otherVector) { var newVector = this.getCopy(); newVector.x /= otherVector.x; newVector.y /= otherVector.y; return newVector; } this.stretch = function(length) { var newVector = this.getCopy(); newVector.x *= length; newVector.y *= length; return newVector; } this.rotate = function(degrees) { var ca = Math.cos(degrees * (Math.PI / 180)); var sa = Math.sin(degrees * (Math.PI / 180)); return new vector(ca*this.x - sa*this.y, sa*this.x + ca*this.y); } this.deltaAngle = function(otherVector) { var a = this.toAngle() * (Math.PI / 180); var b = otherVector.toAngle() * (Math.PI / 180); return Math.atan2(Math.sin(a - b), Math.cos(a - b)) * (180 / Math.PI) } this.cross = function(otherVector) { return this.x * otherVector.y - this.y * otherVector.x; } this.getCopy = function() { return new vector(this.x, this.y); } }