Math - How to use a percentage that stays within a range?
Having a brain fart here. So, if I have a min and max value, and I want to use a 0 - 1 float range for 0%-100%. How can I make it so that when I input 50%, I will get right in the middle of the min and max?
Comment
Best Answer
Answer by Bunny83 · Apr 12, 2016 at 11:46 PM
Something like that?:
//C#
float Map(float min, float max, float t)
{
return min + t*(max-min);
}
Which is basically what Mathf.Lerp does ^^. "t" should be in range [0-1]
and the returned value is in range [min - max]
.
Example:
float r = Map(3f, 15f, 0.5f); // --> 9
float r = Mathf.Lerp(3f, 15f, 0.5f); // --> 9
Just for the record the inverse of that mapping does exist as well: $$anonymous$$athf.InverseLerp
So
float r = $$anonymous$$athf.InverseLerp(3f, 15f, 9f); // --> 0.5
It's implemented like this:
public static float InverseLerp(float a, float b, float value)
{
if (a != b)
{
return $$anonymous$$athf.Clamp01((value - a) / (b - a));
}
return 0f;
}
The "a != b" check is there to prevent a division by zero.