Skip to content

Instantly share code, notes, and snippets.

@HelKyle
Created October 18, 2017 13:34
Show Gist options
  • Select an option

  • Save HelKyle/970c9d48a45e718fab7c107d0d016d45 to your computer and use it in GitHub Desktop.

Select an option

Save HelKyle/970c9d48a45e718fab7c107d0d016d45 to your computer and use it in GitHub Desktop.
two dimension vector class
class Vector {
constructor (x = 0, y = 0) {
this.x = x
this.y = y
}
static add (vector1, vector2) {
return new Vector (
vector1.x + vector2.x,
vector1.y + vector2.y
)
}
static sub (vector1, vector2) {
return new Vector (
vector1.x - vector2.x,
vector1.y - vector2.y
)
}
static clone (vector) {
return new Vector(vector.x, vector.y)
}
static fromAngle (theta, d) {
return new Vector(d * Math.cos(theta), d * Math.sin(theta))
}
clone () {
return new Vector(this.x, this.y)
}
add (vector) {
this.x += vector.x
this.y += vector.y
return this
}
sub (vector) {
this.x -= vector.x
this.y -= vector.y
return this
}
mult (scale) {
this.x *= scale
this.y *= scale
return this
}
div (scale) {
this.x /= scale
this.y /= scale
return this
}
mag () {
return Math.sqrt(this.x * this.x + this.y * this.y)
}
setMag(mag) {
this.normalize()
this.mult(mag)
return this
}
normalize () {
let m = this.mag()
if (m != 0) {
this.div(m)
}
return this
}
limit (max) {
if (this.mag() > max) {
this.normalize()
this.mult(max)
}
return this
}
heading () {
return -Math.atan2(this.x, this.y)
}
}
export default Vector
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment