Advertisement
badunius

js Vector math

Jul 22nd, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. export class Vector {
  2.   constructor({x = 0, y = 0}) {
  3.     this.x = x
  4.     this.y = y
  5.   }
  6.  
  7.   get qLen() {
  8.     return ((this.x * this.x) + (this.y * this.y))
  9.   }
  10.  
  11.   get length() {
  12.     return Math.sqrt(this.qLen)
  13.   }
  14.  
  15.   add({x = 0, y = 0}) {
  16.     return new Vector({
  17.       x: this.x + x,
  18.       y: this.y + y
  19.     })
  20.   }
  21.  
  22.   sub({x = 0, y = 0}) {
  23.     return new Vector({
  24.       x: this.x - x,
  25.       y: this.y - y
  26.     })
  27.   }
  28.  
  29.   mult(n = 1) {
  30.     return new Vector({
  31.       x: this.x * n,
  32.       y: this.y * n
  33.     })
  34.   }
  35.  
  36.   copy({x = 0, y = 0}) {
  37.     this.x = x
  38.     this.y = y
  39.   }
  40.  
  41.   get norm() {
  42.     const l = this.length || 1
  43.     return new Vector({
  44.       x: this.x / l,
  45.       y: this.y / l
  46.     })
  47.   }
  48.  
  49.   static make(x = 0, y = 0) {
  50.     return new Vector({x, y})
  51.   }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement