Guest User

Untitled

a guest
Apr 27th, 2016
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function Vector(x, y) {
  2.     if (x === undefined)
  3.         x = 0;
  4.     if (y === undefined)
  5.         y = 0;
  6.     this.x = x;
  7.     this.y = y;
  8.  
  9.     this.add = function(x, y) {
  10.         if (y === undefined)
  11.             y = x;
  12.         this.x += x;
  13.         this.y += y;
  14.         return this;
  15.     };
  16.     this.addVector = function(other) {
  17.         this.x += other.x;
  18.         this.y += other.y;
  19.         return this;
  20.     };
  21.     this.subtract = function(x, y) {
  22.         if (y === undefined)
  23.             y = x;
  24.         this.x -= x;
  25.         this.y -= y;
  26.         return this;
  27.     };
  28.     this.subtractVector = function(other) {
  29.         this.x -= other.x;
  30.         this.y -= other.y;
  31.         return this;
  32.     };
  33.     this.multiply = function(x, y) {
  34.         if (y === undefined)
  35.             y = x;
  36.         this.x *= x;
  37.         this.y *= y;
  38.         return this;
  39.     };
  40.     this.multiplyVector = function(other) {
  41.         this.x *= other.x;
  42.         this.y *= other.y;
  43.         return this;
  44.     };
  45.     this.divide = function(x, y) {
  46.         if (y === undefined)
  47.             y = x;
  48.         this.x /= x;
  49.         this.y /= y;
  50.         return this;
  51.     };
  52.     this.divideVector = function(other) {
  53.         this.x /= other.x;
  54.         this.y /= other.y;
  55.         return this;
  56.     };
  57.     this.magnitude = function() {
  58.         return Math.sqrt(this.x * this.x + this.y * this.y);
  59.     };
  60.     this.direction = function() {
  61.         return Math.atan(this.y / this.x);
  62.     };
  63.     this.distance = function(other) {
  64.         return Math.sqrt(Math.pow(this.x - other.x, 2) + Math.pow(this.y - other.y, 2));
  65.     };
  66.     this.crossProduct = function(other) {
  67.         return this.x * other.y - this.y * other.x;
  68.     };
  69.     this.normalize = function() {
  70.         if (this.x == 0 && this.y == 0) {}
  71.         else if (this.x == 0)
  72.             this.divide(1, this.magnitude());
  73.         else if (this.y == 0)
  74.             this.divide(this.magnitude(), 1);
  75.         else
  76.             this.divide(this.magnitude());
  77.         return this;
  78.     };
  79.  
  80.     this.toString = function() {
  81.         return this.x + "," + this.y;
  82.     };
  83.     this.clone = function() {
  84.         return new Vector(this.x, this.y);
  85.     };
  86.     this.equals = function(other) {
  87.         return other.x == this.x && other.y == this.y;
  88.     };
  89. }
Advertisement
Add Comment
Please, Sign In to add comment