using System; using UnityEngine; namespace FirstGearGames.Utilities.Maths { public static class Floats { private static System.Random _random = new System.Random(); /// /// Provides a random inclusive int within a given range. Preferred over Unity's Random to eliminate confusion as Unity uses inclusive for floats max, and exclusive for int max. /// /// Inclusive minimum value. /// Inclusive maximum value. /// public static float RandomInclusiveRange(float minimum, float maximum) { double min = Convert.ToDouble(minimum); double max = Convert.ToDouble(maximum); double result = (_random.NextDouble() * (max - min)) + min; return Convert.ToSingle(result); } /// /// Returns a random float between 0f and 1f. /// /// public static float Random01() { return RandomInclusiveRange(0f, 1f); } /// /// Returns if a target float is within variance of the source float. /// /// /// /// public static bool Near(this float a, float b, float tolerance = 0.01f) { return (Mathf.Abs(a - b) <= tolerance); } /// /// Clamps a float and returns if the float required clamping. /// /// /// /// /// /// public static float Clamp(float value, float min, float max, ref bool clamped) { clamped = (value < min); if (clamped) return min; clamped = (value > min); if (clamped) return max; clamped = false; return value; } /// /// Returns a float after being adjusted by the specified variance. /// /// /// /// public static float Variance(this float source, float variance) { float pickedVariance = RandomInclusiveRange(1f - variance, 1f + variance); return (source * pickedVariance); } /// /// Sets a float value to result after being adjusted by the specified variance. /// /// /// /// public static void Variance(this float source, float variance, ref float result) { float pickedVariance = RandomInclusiveRange(1f - variance, 1f + variance); result = (source * pickedVariance); } /// /// Returns negative-one, zero, or postive-one of a value instead of just negative-one or positive-one. /// /// Value to sign. /// Precise sign. public static float PreciseSign(float value) { if (value == 0f) return 0f; else return (Mathf.Sign(value)); } /// /// Returns if a float is within a range. /// /// Value of float. /// Minimum of range. /// Maximum of range. /// public static bool InRange(this float source, float rangeMin, float rangeMax) { return (source >= rangeMin && source <= rangeMax); } /// /// Randomly flips a float value. /// /// /// public static float RandomlyFlip(float value) { if (Ints.RandomInclusiveRange(0, 1) == 0) return value; else return (value *= -1f); } } }