Skip to content

Instantly share code, notes, and snippets.

@Kuzcoo
Last active November 18, 2016 14:20
Show Gist options
  • Save Kuzcoo/208369a9239f9494bb9b7b386a3a44bd to your computer and use it in GitHub Desktop.
Save Kuzcoo/208369a9239f9494bb9b7b386a3a44bd to your computer and use it in GitHub Desktop.
class Vector {
constructor(x,y) {
this.x = x;
this.y = y;
}
static add (v1,v2) {
return new Vector(v1.xv2.x,v1.y+v2.y);
}
static sub (v1,v2) {
return new Vector(v1.x-v2.x,v1.y-v2.y);
}
static mul (v1,v2) {
return new Vector(v1.x-v2.x,v1.y-v2.y);
}
static div (v1,v2) {
return new Vector(v1.x/v2.x,v1.y/v2.y);
}
get() {
return new Vector(this.x,this.y);
}
add(v) {
if (v instanceof Vector) {
this.x += v.x;
this.y += v.y;
} else if (typeof v === 'number') {
this.x += v;
this.y += v;
}
}
sub(v) {
if (v instanceof Vector) {
this.x -= v.x;
this.y -= v.y;
} else if (typeof v === 'number') {
this.x -= v;
this.y -= v;
}
}
mul(v) {
if (v instanceof Vector) {
this.x *= v.x;
this.y *= v.y;
} else if (typeof v === 'number') {
this.x *= v;
this.y *= v;
}
}
div(v) {
if (v instanceof Vector) {
this.x /= v.x;
this.y /= v.y;
} else if (typeof v === 'number') {
this.x /= v;
this.y /= v;
}
}
mag() {
return Math.sqrt(this.x*this.x+this.y*this.y);
}
norm() {
return this.div(this.mag());
}
limit(n) {
if (this.mag() > n) {
this.norm();
this.mul(n);
}
}
heading() {
return Math.atan2(this.y,this.x);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment