- Home /
Problems With Mathf.InverseLerp
I've run into an issue that's driving me insane, because I've read all of the questions on the matter, and although the answers seem to work for the other askers, they simply don't for me. I have an int variable called "boostValue" that I am limiting to a minimum of 0 and a maximum of 300. I have another int variable called "barWidth", which I need to limit to a minimum of 4 and a maximum of about 240, though I'm not set on the exact max value just yet. Now, I need the barWidth value to be set within its range to the equivalent of the boostValue within ITS range. I'll also need to do this for a different int variable similar to barWidth, only I need it to be calculated to a negative value. Either way, I need both of them to be calculated (within their range) according to the current value of boostMeter (within its range). I've tried everything I can find, and everything I can think of, but the barWidth value either goes up by a TINY amount, or just stays at 0. By "tiny amount", I mean I would have to set the boostValue to some ridiculously high number just to get the barWidth to something like 10. I've been messing around with this and trying different ideas for so long now, that I can hardly even remember everything the script has done that isn't what I need. I can't even tell if I'm on the right track anymore. I could be doing something completely different now and I don't even realize it. This is so simple, but it just won't work for me.
barWidth = Mathf.InverseLerp(4, 240, boostValue);
That's the basis of what I need, though I'm not even sure how I would make it take into account the limits of the boostValue. If someone could please show me what I'm doing wrong here, and maybe show me how I could pull this off, I would be very grateful.
You lose me with the negative value comment. Your small movement problem may be the result of integer math or the result of a calculation issue. You don't show enough code for me to see what is really going on. But you might be better off using floats and then converting back to an int in the end. Here is your calculation for barWidth:
barWidth = $$anonymous$$athf.Round(4.0 + (240.0 - 4.0) * (float)boostValue / 300.0);
Answer by Roland1234 · Nov 27, 2013 at 06:26 PM
It sounds like you need something like this:
public static class MathHelper
{
public static float RangeValueTranslate(float start0, float end0, float value0, float start1, float end1)
{
var t1 = (value0 - start0) / (end0 - start0);
return start1 + ((end1 - start1) * t1);
}
}
which you would use like this:
var barWidthValue = MathHelper.RangeValueTranslate(boostValueMin, boostValueMax, boostValue, barWidthMin, barWidthMax);
Having to cast if necessary, but it shouldn't be a problem (just note that you will lose precision if casting your result to an int). Should work fine for ranges going in either direction (negative or positive).
Oh - and watch out for divide by zero possibilities.