phaser/src/math/Percent.js

54 lines
1.5 KiB
JavaScript
Raw Normal View History

2018-02-12 16:01:20 +00:00
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
2017-10-06 03:52:41 +00:00
/**
* Work out what percentage `value` is of the range between `min` and `max`.
* If `max` isn't given then it will return the percentage of `value` to `min`.
*
2017-10-17 20:31:45 +00:00
* You can optionally specify an `upperMax` value, which is a mid-way point in the range that represents 100%, after which the % starts to go down to zero again.
2017-10-06 03:52:41 +00:00
*
* @function Phaser.Math.Percent
* @since 3.0.0
*
* @param {number} value - The value to determine the percentage of.
* @param {number} min - The minimum value.
* @param {number} [max] - The maximum value.
* @param {number} [upperMax] - The mid-way point in the range that represents 100%.
2017-10-06 03:52:41 +00:00
*
* @return {number} A value between 0 and 1 representing the percentage.
2017-10-06 03:52:41 +00:00
*/
2017-09-15 03:04:51 +00:00
var Percent = function (value, min, max, upperMax)
{
2017-09-15 03:04:51 +00:00
if (max === undefined) { max = min + 1; }
2017-09-15 03:04:51 +00:00
var percentage = (value - min) / (max - min);
if (percentage > 1)
{
2017-09-15 03:04:51 +00:00
if (upperMax !== undefined)
{
percentage = ((upperMax - value)) / (upperMax - max);
if (percentage < 0)
{
percentage = 0;
}
}
else
{
percentage = 1;
}
}
2017-09-15 03:04:51 +00:00
else if (percentage < 0)
{
2017-09-15 03:04:51 +00:00
percentage = 0;
}
2017-09-15 03:04:51 +00:00
return percentage;
};
module.exports = Percent;