Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2020
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* 3D Vector type
  2.  
  3. fields:
  4.     number x
  5.     number y
  6.     number z
  7.  
  8. consructors:
  9.     default(number x, number y, number z) aka new keyword
  10.     zero()
  11.     fill(number) fills each field with the same value
  12.     copy(vector) creates new vector the same as the old
  13.  
  14. methods:
  15.     add(vector) => vector, object keeps unchanged
  16.     sub(vector) => vector, object keeps unchanged
  17.     mul(vector) => vector, object keeps unchanged
  18.     div(vector) => vector, object keeps unchanged
  19.     negative() => vector, object keeps unchanged
  20.     scale(number) => vector, object keeps unchanged
  21.     cross(vector) => vector, object keeps unchanged
  22.     dot(vector) => number
  23.     length() => number
  24.     normalize() => vector, object keeps unchanged
  25.  
  26.     prototype.toString() => string
  27. */
  28.  
  29. function Vector(x, y, z)
  30. {
  31.     this.x = x;
  32.     this.y = y;
  33.     this.z = z;
  34.  
  35.     this.add = (a) => new Vector(this.x + a.x, this.y + a.y, this.z + a.z);
  36.  
  37.     this.sub = (a) => new Vector(this.x - a.x, this.y - a.y, this.z - a.z);
  38.  
  39.     this.mul = (a) => new Vector(this.x * a.x, this.y * a.y, this.z * a.z);
  40.  
  41.     this.div = (a) => new Vector(this.x / a.x, this.y / a.y, this.z / a.z);
  42.  
  43.     this.negative = () => new Vector(-this.x, -this.y, -this.z);
  44.  
  45.     this.scale = (value) => new Vector(this.x * value, this.y * value, this.z * value);
  46.  
  47.     this.cross = (a) => new Vector(
  48.         this.y * a.z - this.z * a.y,
  49.         this.x * a.z - this.z * a.x,
  50.         this.x * a.y - this.y * a.x
  51.     );
  52.  
  53.     this.dot = (a) => this.x * a.x + this.y * a.y + this.z * a.z;
  54.  
  55.     this.length = () => Math.sqrt(this.dot(this));
  56.  
  57.     this.normalize = () => this.scale(1 / this.length());
  58. }
  59.  
  60. Vector.zero = () => new Vector(0, 0, 0);
  61.  
  62. Vector.fill = (value) => new Vector(value, value, value);
  63.  
  64. Vector.copy = (a) => new Vector(a.x, a.y, a.z);
  65.  
  66. Vector.prototype.toString = function()
  67. {
  68.     return `x: ${this.x}\ty: ${this.y}\tz: ${this.z}`;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement