- Home /
Change value according to Y position of an object?
Hi,
I have an obejct which I can move up and down on the Y-axis and is limited to a min and max value. Let's say you can move it from a random value like 0.173 up to 0.298.
I then would like to have a different value which changes dynamically from e.g. -30 to +30 depending on the objects position on its Y-axis. Ideally this value would change in +-0.5 steps. Right now I can only think of manually "binding" the value on the y-axis to the other value like 0.173 = -30, 0.177 = -29.5, 0.181 = -29,...
But that definitely doesn't seem right at all...
Any help would be much appreciated!
Thanks in advance! :)
Answer by Namey5 · Apr 06, 2020 at 08:33 AM
You can get there with a bunch of functions. I'll explain what each step does;
//These are the min/max for your object's y-axis (you would already have these)
float yMin = 0.2f;
float yMax = 0.4f;
//These are the min/max for the function output (the range to convert to)
float fMin = -30f;
float fMax = 30f;
//The size of each individual step
float step = 0.5f;
...
//y-axis position of the object
float y = transform.position.y;
//Re-map into a range of [0f,1f]. If you don't want the function to go outside the range, you can clamp this using Mathf.Clamp01()
float t = (y - yMin) / (yMax - yMin);
//Using t, re-map into the range of the function
float range = Mathf.Lerp (fMin, fMax, t);
//This is the final value. We scale by the step amount, round down to the nearest integer, then scale back into the original range. This allows you to step through a range at a specific interval
float f = Mathf.Floor (range / step) * step;
Thanks a lot for this in depth answer! I will test it right now and will let you know if it works!
Answer by Crystall21 · Apr 06, 2020 at 03:15 PM
Take a look at this https://forum.unity.com/threads/re-map-a-number-from-one-range-to-another.119437/
Your answer
Follow this Question
Related Questions
(C#) Return Float Variable to previous value 1 Answer
Positive to negative not working? 1 Answer
Inverse the mouse position value 2 Answers