JSFiddle - React, Tailwind, and code Playground
by Darby Rathbone
JavaScript
var Vector = (function () {
Vector.mult = function (v1, s) {
return new Vector(v1.x * s, v1.y * s);
};
Vector.divide = function (v1, s) {
return new Vector(v1.x / s, v1.y / s);
};
/* Adds two vectors and returns the product.
*/
Vector.add = function (v1, v2) {
return new Vector(v1.x + v2.x, v1.y + v2.y);
};
/* Subtracts v2 from v1 and returns the product.
*/
Vector.sub = function (v1, v2) {
return new Vector(v1.x - v2.x, v1.y - v2.y);
};
/* Projects one vector (v1) onto another (v2)
*/
Vector.project = function (v1, v2) {
return v1.clone()
.scale((v1.dot(v2)) / v1.magSq());
};
/* Creates a new Vector instance.
*/
function Vector(x, y) {
this.x = x !== null ? x : 0.0;
this.y = y !== null ? y : 0.0;
}
/* Sets the components of this vector.
*/
Vector.prototype.set = function (x, y) {
this.x = x;
this.y = y;
return this;
};
/* Add a vector to this one.
*/
Vector.prototype.add = function (v) {
this.x += v.x;
this.y += v.y;
return this;
};
/* Subtracts a vector from this one.
*/
Vector.prototype.sub = function (v) {
this.x -= v.x;
this.y -= v.y;
return this;
};
/* Scales this vector by a value.
*/
Vector.prototype.scale = function (f) {
this.x *= f;
this.y *= f;
return this;
};
/* Computes the dot product between vectors.
*/
Vector.prototype.dot = function (v) {
return this.x * v.x + this.y * v.y;
};
/* Computes the cross product between vectors.
*/
...