Skip to content

Instantly share code, notes, and snippets.

@kunukn
Created April 28, 2019 21:07
Show Gist options
  • Select an option

  • Save kunukn/572e4fc6e38c2b8588fc0fc78482ebc8 to your computer and use it in GitHub Desktop.

Select an option

Save kunukn/572e4fc6e38c2b8588fc0fc78482ebc8 to your computer and use it in GitHub Desktop.
Vector 2D
class Vector {
constructor(x, y) {
this.x = x || 0;
this.y = y || 0;
}
toString = () => `(${this.x}, ${this.y})`;
_limitApply = () => {
if (this.limitValue && this.mag() > this.limitValue)
this.setMag(this.limitValue);
};
add = v => {
this.x += v.x;
this.y += v.y;
this._limitApply();
};
static add = (v1, v2) => new Vector(v1.x + v2.x, v1.y + v2.y);
sub = v => {
this.x -= v.x;
this.y -= v.y;
this._limitApply();
};
static sub = (v1, v2) => new Vector(v1.x - v2.x, v1.y - v2.y);
div = v => {
this.x /= value;
this.y /= value;
this._limitApply();
};
static div = (v, value) => new Vector(v.x / value, v.y / value);
mult = value => {
this.x *= value;
this.y *= value;
this._limitApply();
};
static mult = (v, value) => new Vector(v.x * value, v.y * value);
mag = () => Math.sqrt(this.x * this.x + this.y * this.y);
magSq = () => {
let mag = this.mag();
return mag * mag;
};
normalize = () => {
let mag = this.mag();
this.x /= mag;
this.y /= mag;
};
setMag = value => {
this.normalize();
this.mult(value);
};
limit = value => {
this.limitValue = value;
this._limitApply();
};
clone = () => {
let vector = new Vector(this.x, this.y);
if (this.limit) vector.limit = this.limit;
return vector;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment