Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value to be from 0 to 1?

Tags:

c#

I tried to look for an answer for this problem but I guess nobody has needed something like this or it's something super simple that I just can't get my head around. So:

I have a value that changes from 45 to 20.

I'd need a value that goes from 0 to 1 in same time as 45 goes to 20. I know that 45 - 20 = 25 and that would be my 100% and hence the number 1.

I'd implement this in Lerp value like this:

public float minHeight = 10.0f;
public float maxHeight = 30.0f;
public float convertedValue;

convertedValue = ??? (Something like 45 - 20 = 25 = 100%) * 0.01;

newValue = Mathf.Lerp(minHeight, maxHeight, convertedValue);

Hopefully someone can help me. Im fairly new to coding and I was just wondering if this is possible. Thanks for your time!

like image 314
Mureahko Avatar asked Oct 19 '25 04:10

Mureahko


2 Answers

I believe the calculation matching your explanation would be

newValue = (convertedValue - minHeight) / (maxHeight - minHeight);

i.e. newValue = 0 @ minHeight, and 1 @ maxHeight

Edit

I've never seen Lerp before, but apparantly it is simple linear interpolation.

However, from MSDN

Lerp is defined as

value1 + (value2 - value1) * amount

i.e. in your example convertedValue should be the fraction, and the answer is the interpolated result, meaning that your question / my (and Esailja's) interpretation thereof is inverted :)

i.e.

Mathf.Lerp(10.0, 30.0, 0.5) = 20.0

whereas

InvertedLerp(10.0, 30.0, 20) = 0.5 // My / Esailja's calc

:)

like image 133
StuartLC Avatar answered Oct 21 '25 18:10

StuartLC


I recognize your Mathf.Lerp as part of the Unity3D APIs. A function there already exists to do what you're trying to do: Mathf.InverseLerp. You should use this.

like image 20
Tim S. Avatar answered Oct 21 '25 18:10

Tim S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!