Reputation: 43
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!
Upvotes: 4
Views: 6901
Reputation: 56556
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.
Upvotes: 2
Reputation: 107317
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
:)
Upvotes: 7
Reputation: 1561
public float AnswerMureahkosQuestion(float input)
{
const float minValue = 20;
const float maxValue = 45;
float range = maxValue - minValue;
// nominalise to 1
// NOTE: you don't actually need the *1 but it reads better
float answer = (input+0.00001/*prevents divbyzero errors*/) / range * 1;
// invert so 45 is 0 and 20 is 1
answer = 1 - answer;
return answer;
}
Upvotes: 0
Reputation: 118
How about a property?
public int neededvalue
{
get
{
if (value == 45)
return 1;
else if (value == 20)
return 0
else
throw new Exception("wrong input");
}
}
public float neededvaluealternative
{
get
{
return (value - 20) / (45 - 20)
}
}
Upvotes: 0
Reputation: 140228
public float minHeight = 10.0f;
public float maxHeight = 30.0f;
float curHeight = 25.0f;
float newValue = ( curHeight - minHeight ) / ( maxHeight - minHeight );
Upvotes: 1
Reputation: 122
minvalue=20
maxvalue=45
result=(aktvalue-minvalue)/(maxvalue-minvalue)
something like this?
Upvotes: 0