-
Notifications
You must be signed in to change notification settings - Fork 0
/
rv-util.js
125 lines (113 loc) · 2.48 KB
/
rv-util.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/* Robert's Utilities!
*
* These are a set of utility functions that I use all the damn time.
* Documentation forthcoming.
*
*
* © Robert Vinluan, 2013
*/
(function(){
var ro = {};
/* Map
*
* Given a value and a range,
* maps that value into a second range.
*
* returns the corresponding value in the second range.
*
*
*
*/
ro.map = function(value, start1, stop1, start2, stop2) {
if(value < start1) {
return start2;
} else if (value > stop1) {
return stop2;
}
//figure out how wide each range is
var range1 = stop1 - start1;
var range2 = stop2 - start2;
//find value in between 0 and 1
var normalizedValue = (value - start1) / range1;
//convert into range2
return start2 + (normalizedValue * range2);
}
/* Distance
*
* Find the distance between two points.
*
*/
ro.dist = function(x1, y1, x2, y2) {
var x = Math.abs(x1 - x2);
var y = Math.abs(y1 - y2);
return Math.sqrt((x*x) + (y*y));
}
/* Random
*
* returns a random number between 0 and max,
* or given two arguments, a random number between min and max.
*
*/
ro.random = function(min, max) {
if(arguments.length === 0) {
return Math.random();
} else if(arguments.length === 1) {
return Math.random() * min;
} else {
return min + (Math.random() * (max - min));
}
}
/* ToRadians
*
* converts from degrees to radians.
*
*/
ro.toRad = function(deg) {
return deg * ( Math.PI / 180);
}
/* Same
*
* returns true if all arguments strictly equal each other
*
*/
ro.same = function() {
for(var i = 0; i < arguments.length - 1; i++) {
if(arguments[i] !== arguments[i+1]) {
return false;
}
}
return true;
}
/* MoveValueTowards
*
* moves a value towards another value by 1
*
*/
ro.moveValueTowards = function(val1, val2) {
var dist = Math.abs(val1 - val2);
if(val1 === val2 || dist <= 1 ) {
return val2;
} else if(val1 < val2) {
return val1 + 5;
} else {
return val1 - 5;
}
}
/* Any
*
* returns true if test matches any element in the array
*
*
*
*
*/
ro.any = function(test, array) {
for(i in array) {
if(array[i] === test) {
return true;
}
}
return false;
}
window.rvutil = ro;
})();