The question is answered, right answer was accepted
Change variable depending on other variable
I'm trying to make 2 variables change depending on change in the other variable.
Example: var1 has a range of 26-100, var2 has a range of 12-30. Then to match up 26 has to be equal to 12, and 100 to 30. So when one variable goes up a certain % the other matches.
How would one do this?
Answer by Bilelmnasser · Oct 06, 2017 at 01:03 PM
Hi, let's try your Example: var1 has a range of 26-100, var2 has a range of 12-30. Then to match up 26 has to be equal to 12, and 100 to 30. So when one variable goes up a certain % the other matches :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test : MonoBehaviour {
private float x;
public float X
{
get { return x; }
set
{ // we clamp value to keep x in range between (26 and 100)
x = Mathf.Clamp( value,26.0f,100.0f);
// we calculate the new value of y based on the new value of x
y =(((x-26.0f)/(100.0f-26.0f))*(30.0f-12.0f))+12.0f ;
print( "When X = " + X + " Y = " + Y );
}
}
private float y;
public float Y
{
get { return y; }
set
{ // we clamp value to keep y in range between (12 and 30)
y = Mathf.Clamp( value , 12.0f , 30.0f );
// we calculate the new value of x based on the new value of y
x = ( ( ( y - 12.0f ) / ( 30.0f - 12.0f ) ) * ( 100.0f - 26.0f ) ) + 26.0f;
print( "When Y = "+Y+" X = "+X );
}
}
// Use this for initialization
void Start () {
X = -500.0f;
X = 26.0f;
X = 75.0f;
X = 100.0f;
X = 10000.0f;
Y = 0.0f;
Y = 12.0f;
Y = 30.0f;
Y = 50.0f;
Y = 100.0f;
}
}
Result here :
Answer by elenzil · Oct 06, 2017 at 07:55 PM
this is exactly what Lerp() and InverseLerp() are for.
float normalizedValue = Mathf.InverseLerp(26, 100, var1);
float var2 = Mathf.Lerp(12, 30, normalizedValue);
this is functionally the same math as the core of @Bilelmnasser 's answer, but i find it a bit more readable.
Follow this Question
Related Questions
Predict the hit position 0 Answers
Unity Math is Wrong for Some Reason 0 Answers
Check if a point is on the right or left of a vector? 2 Answers
Money-system for decillionare game 1 Answer