github.com/turtlemonvh/terraform@v0.6.9-0.20151204001754-8e40b6b855e8/website/source/assets/javascripts/lib/Vector.js (about)

     1  (function(global){ 'use strict';
     2  
     3  var Vector = function(x, y){
     4  	this.x = x || 0;
     5  	this.y = y || 0;
     6  };
     7  
     8  Vector.prototype = {
     9  
    10  	clone: function(){
    11  		return new Vector(this.x, this.y);
    12  	},
    13  
    14  	add: function(vec){
    15  		this.x += vec.x;
    16  		this.y += vec.y;
    17  		return this;
    18  	},
    19  
    20  	sub: function(vec){
    21  		this.x -= vec.x;
    22  		this.y -= vec.y;
    23  		return this;
    24  	},
    25  
    26  	subVal: function(val){
    27  		this.x -= val;
    28  		this.y -= val;
    29  		return this;
    30  	},
    31  
    32  	mult: function(mul){
    33  		this.x *= mul;
    34  		this.y *= mul;
    35  		return this;
    36  	},
    37  
    38  	div: function(div){
    39  		if (div === 0) {
    40  			return this;
    41  		}
    42  		this.x /= div;
    43  		this.y /= div;
    44  		return this;
    45  	},
    46  
    47  	mag: function(){
    48  		return Math.sqrt(
    49  			this.x * this.x +
    50  			this.y * this.y
    51  		);
    52  	},
    53  
    54  	limit: function(max){
    55  		if (this.mag() > max) {
    56  			this.normalize();
    57  			this.mult(max);
    58  		}
    59  		return this;
    60  	},
    61  
    62  	normalize: function(){
    63  		var mag = this.mag();
    64  		if (mag === 0) {
    65  			return this;
    66  		}
    67  		this.div(mag);
    68  		return this;
    69  	},
    70  
    71  	heading: function(){
    72  		return Math.atan2(this.y, this.x);
    73  	},
    74  
    75  	set: function(vec){
    76  		this.x = vec.x;
    77  		this.y = vec.y;
    78  		return this;
    79  	}
    80  
    81  };
    82  
    83  Vector.add = function(vec1, vec2){
    84  	return vec1.clone().add(vec2.clone());
    85  };
    86  
    87  Vector.sub = function(vec1, vec2){
    88  	return vec1.clone().sub(vec2.clone());
    89  };
    90  
    91  Vector.mult = function(vec, mult){
    92  	return vec.clone().mult(mult);
    93  };
    94  
    95  Vector.div = function(vec, div){
    96  	return vec.clone().div(div);
    97  };
    98  
    99  // Ripped from processing
   100  Vector.random2D = function(){
   101  	var angle = Math.random(0, 1) * Math.PI * 2;
   102  	return new Vector(Math.cos(angle), Math.sin(angle));
   103  };
   104  
   105  Vector.coerce = function(obj){
   106  	return new Vector(obj.x, obj.y);
   107  };
   108  
   109  global.Vector = Vector;
   110  
   111  })(this);