dabbjs
Version:
general javascript library
80 lines (79 loc) • 2.11 kB
JavaScript
//inspired by
//https://evanw.github.io/lightgl.js/docs/vector.html
export class Vector2D {
constructor(x, y) {
this.x = x;
this.y = y;
}
/**
* returns the length of the vector
*/
length() { return Math.sqrt(this.dot(this)); }
/**
* returns DOT product of these vectors
* @param v vector 2d
*/
dot(v) { return this.x * v.x + this.y * v.y; }
/**
* returns the Determinant of these vectors
* @param v vector 2d
*/
det(v) { return this.x * v.y - this.y * v.x; }
/**
* returns the angle between these two vectors
* @param v vector 2d
*/
angleTo(v) { return Math.atan2(this.det(v), this.dot(v)); }
/**
* returns the vector addition
* @param v vector2d or number
*/
add(v) {
if (typeof v === "number")
return new Vector2D(this.x + v, this.y + v);
else
return new Vector2D(this.x + v.x, this.y + v.y);
}
/**
* returns the vector subtraction
* @param v vector2d or number
*/
sub(v) {
if (typeof v === "number")
return new Vector2D(this.x - v, this.y - v);
else
return new Vector2D(this.x - v.x, this.y - v.y);
}
/**
* returns the vector multiplication
* @param v vector2d or number
*/
mul(v) {
if (typeof v === "number")
return new Vector2D(this.x * v, this.y * v);
else
return new Vector2D(this.x * v.x, this.y * v.y);
}
/**
* returns the vector division
* @param v vector2d or number
*/
div(v) {
if (typeof v === "number")
return new Vector2D(this.x / v, this.y / v);
else
return new Vector2D(this.x / v.x, this.y / v.y);
}
/**
* returns the Unit vector
*/
unit() { return this.div(this.length()); }
/**
* returns a clone of this vector
*/
clone() { return new Vector2D(this.x, this.y); }
/**
* returns the XY plane origin/empty vector
*/
static empty() { return new Vector2D(0, 0); }
}