namespace Ecosystem.utility;
public class Math
{
///
/// Re-maps a number from one range to another.
/// For example, calling map(2, 0, 10, 0, 100) returns 20.
/// The first three arguments set the original value to 2
/// and the original range from 0 to 10. The last two
/// arguments set the target range from 0 to 100. 20's
/// position in the target range [0, 100] is proportional
/// to 2's position in the original range [0, 10].
/// The sixth parameter, withinBounds, is optional.
///
///
/// By default, map() can return values outside the
/// target range. For example, map(11, 0, 10, 0, 100)
/// returns 110. Passing true as the sixth parameter
/// constrains the remapped value to the target range.
/// For example, map(11, 0, 10, 0, 100, true) returns 100.
///
/// The value to be remapped
/// Lower bound of the value's current range
/// Upper bound of the value's current range
/// Lower bound of the value's target range
/// Upper bound of the value's target range
/// Constrain the value to the newly mapped value
/// Remapped number
public static float Map(float value, float start1, float stop1, float start2, float stop2, bool withinBounds = false)
{
var newval = (value - start1) / (stop1 - start1) * (stop2 - start2) + start2;
if (!withinBounds) {
return newval;
}
if (start2 < stop2) {
return float.Clamp(newval, start2, stop2);
} else {
return float.Clamp(newval, stop2, start2);
}
}
public static double Map(double value, double start1, double stop1, double start2, double stop2, bool withinBounds = false)
{
var newval = (value - start1) / (stop1 - start1) * (stop2 - start2) + start2;
if (!withinBounds) {
return newval;
}
if (start2 < stop2) {
return double.Clamp(newval, start2, stop2);
} else {
return double.Clamp(newval, stop2, start2);
}
}
}