I like Tobias Springer's solution, but you can also create a vector object with utilities:
Vector = function(x, y, z) { this._init(x, y, z); }; Vector.prototype = { constructor: Vector, x: null, y: null, z: null, /** * Add documentation! */ _init: function(x, y, z) { this.x = x; this.y = y; this.z = z; }, add: function(otherVector) { return new Vector(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z); }, scalarProduct: function(otherVector) { return this.x * otherVector.x + this.y * otherVector.y + this.z * otherVector.z; }, distance: function(otherVector) { return Math.sqrt(Math.pow((this.x-otherVector.x),2) + Math.pow((this.y-otherVector.y),2) + Math.pow((this.z-otherVector.z),2)); }
So you would use it like this:
var vector1 = new Vector (1, 1, 1); var vector2 = new Vector (1, 0, 1); var addedVector = vector1.add(vector2);
source share