Skip to content

Instantly share code, notes, and snippets.

@KrofDrakula
Created July 23, 2016 08:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KrofDrakula/438fb6b07a8179040450f638bfa17ed2 to your computer and use it in GitHub Desktop.
Save KrofDrakula/438fb6b07a8179040450f638bfa17ed2 to your computer and use it in GitHub Desktop.
A mutable 2D vector class, made for real-time graphics in JS
class Vec2d {
constructor(x, y) { this.reset(x, y); }
get mag() { return Math.sqrt(this.dot(this)); }
clone() { return new Vec2d(this.x, this.y); }
reset(x, y) { this.x = x; this.y = y; return this; }
neg() { return this.scale(-1); }
norm() {
let m = this.mag;
if (m > 0) return this.scale(1 / m);
return this;
}
add(a, b) {
let x, y;
if (a instanceof Vec2d) {
x = a.x; y = a.y;
} else {
x = a; y = b;
}
this.x += x;
this.y += y;
return this;
}
sub(a, b) {
let x, y;
if (a instanceof Vec2d) {
x = a.x; y = a.y;
} else {
x = a; y = b;
}
this.x -= x;
this.y -= y;
return this;
}
scale(a) {
this.x *= a;
this.y *= a;
return this;
}
dot(a, b) {
let x, y;
if (a instanceof Vec2d) {
x = a.x; y = a.y;
} else {
x = a; y = b;
}
return this.x * x + this.y * y;
}
static add(a, b) { return a.clone().add(b); }
static sub(a, b) { return a.clone().sub(b); }
static dot(a, b) { return a.dot(b); }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment