Skip to content

Commit a6302cd

Browse files
James LowreyJames Lowrey
authored andcommitted
fixed between() docs and updated it to accept negative numbers, default values, and auto-orders min/max parameters if they're input wrong. Added a random() function that does the same but returns floats instead of integers
1 parent b1473c5 commit a6302cd

1 file changed

Lines changed: 37 additions & 5 deletions

File tree

src/math/Math.js

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,17 +24,49 @@ Phaser.Math = {
2424
PI2: Math.PI * 2,
2525

2626
/**
27-
* Returns a number between the `min` and `max` values.
27+
* Returns a random float in the range `[min, max)`. If these parameters are not in order than they will be put in order.
28+
* Default is 0 for `min` and 1 for `max`.
2829
*
2930
* @method Phaser.Math#between
30-
* @param {number} min - The minimum value. Must be positive, and less than 'max'.
31-
* @param {number} max - The maximum value. Must be position, and greater than 'min'.
32-
* @return {number} A value between the range min to max.
31+
* @param {number} min - The minimum value. Must be a Number.
32+
* @param {number} max - The maximum value. Must be a Number.
33+
* @return {number} A floating point number between the range min to max.
34+
*/
35+
random: function (min, max) {
36+
if (min === undefined) { min = 0; }
37+
if (max === undefined) { max = 1; }
38+
39+
if ( min < max ) {
40+
var temp = min;
41+
min = max;
42+
max = temp;
43+
}
44+
45+
return Math.random() * (max - min) + min;
46+
},
47+
48+
/**
49+
* Returns a random integer in the range `[min, max]`. If these parameters are not in order than they will be put in order.
50+
* Default is 0 for `min` and 1 for `max`.
51+
*
52+
* @method Phaser.Math#between
53+
* @param {number} min - The minimum value. Must be a Number.
54+
* @param {number} max - The maximum value. Must be a Number.
55+
* @return {number} A floating point number between the range min to max.
3356
*/
3457
between: function (min, max) {
58+
if (min === undefined) { min = 0; }
59+
if (max === undefined) { max = 1; }
3560

36-
return Math.floor(Math.random() * (max - min + 1) + min);
61+
if ( min < max ) {
62+
var temp = min;
63+
min = max;
64+
max = temp;
65+
}
3766

67+
min = Math.ceil(min);
68+
max = Math.floor(max);
69+
return Math.floor(Math.random() * (max - min + 1)) + min;
3870
},
3971

4072
/**

0 commit comments

Comments
 (0)