Files

94 lines
3.3 KiB
C#
Raw Permalink Normal View History

2026-06-02 18:57:47 -04:00
using UnityEngine;
namespace BracerLib.Utility
{
/// <summary>
/// Inclusivity determination for a comparison between a lower and upper bound number.
/// </summary>
public enum BoundsInclusivity
{
/// <summary>
/// Neither bound is included.
/// </summary>
None,
/// <summary>
/// Both bounds are included.
/// </summary>
Both,
/// <summary>
/// Left bound is included.
/// </summary>
Left,
/// <summary>
/// Right bound is included.
/// </summary>
Right
}
public static class MathUtility
{
public const float TWO_PI = 2f * Mathf.PI;
/// <summary>
/// Overflow of a value between two bounds. Values lower than the lowerbound will cycle from the upperbound and vice versa.
/// </summary>
/// <param name="value">The value to overflow, if needed.</param>
/// <param name="lowerBound">The lowerbound number to be checked against.</param>
/// <param name="upperBound">The upperbound number to be checked against.</param>
/// <returns>Inclusive value within the bounds.</returns>
public static int KeepWithinBounds(int value, int lowerBound, int upperBound)
{
var diff = upperBound - lowerBound + 1;
var v = (value - lowerBound) % diff + diff;
v = v % diff + lowerBound;
return v;
}
/// <summary>
/// Determine if a value is between a lower and upper bound set of numbers.
/// </summary>
/// <param name="value">The value to check.</param>
/// <param name="lowerBound">The lower bound of the comparison.</param>
/// <param name="upperBound">The upper bound of the comparison.</param>
/// <param name="inclusivity">The inclusivity bounds for the comparison.</param>
/// <returns>Whether the value is between the two numbers based on the inclusivity passed.</returns>
public static bool IsBetween(
int value,
int lowerBound,
int upperBound,
BoundsInclusivity inclusivity = BoundsInclusivity.None
)
{
var result = inclusivity switch
{
BoundsInclusivity.Both => value >= lowerBound && value <= upperBound,
BoundsInclusivity.Left => value >= lowerBound && value < upperBound,
BoundsInclusivity.Right => value > lowerBound && value <= upperBound,
_ => value > lowerBound && value < upperBound
};
return result;
}
/// <inheritdoc cref="IsBetween(int,int,int,BracerLib.Utility.BoundsInclusivity)" />
public static bool IsBetween(
float value,
float lowerBound,
float upperBound,
BoundsInclusivity inclusivity = BoundsInclusivity.None
)
{
var result = inclusivity switch
{
BoundsInclusivity.Both => value >= lowerBound && value <= upperBound,
BoundsInclusivity.Left => value >= lowerBound && value < upperBound,
BoundsInclusivity.Right => value > lowerBound && value <= upperBound,
_ => value > lowerBound && value < upperBound
};
return result;
}
}
}