Created
July 23, 2016 08:26
-
-
Save KrofDrakula/438fb6b07a8179040450f638bfa17ed2 to your computer and use it in GitHub Desktop.
A mutable 2D vector class, made for real-time graphics in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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