Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Easier way to calculate an adjusted proportion?

Discussion in 'Scripting' started by the_garlic_monkey, Jul 14, 2023.

  1. the_garlic_monkey

    the_garlic_monkey

    Joined:
    Sep 29, 2017
    Posts:
    1
    Sorry if this has been answered before, but I have no clue what to actually call this, so all I have to go off is a description.

    If I input a float Na that exists within range A, I want to output float Nb that is the same proportion within range B.

    Say I have a float A with range (2,4).
    Then I have float B with range (15,23).
    If I input 3 (halfway between 2 and 4), it should output 19 (halfway between 15 and 23).

    Here's what I've written for doing the calculations:
    Code (CSharp):
    1.    
    2. float AdjustedProportion(float input)
    3.     {
    4.         //Convert to percent of first range
    5.         float percent = (maxA - input) / (maxA - minA);
    6.  
    7.         //Convert back to number within second range
    8.         return (maxB - (percent * (maxB - minB)));
    9.     }
    10.  
    This works fine, but I was wondering if there is a better way to write this or if Unity has a built in Mathf function specifically for this.
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,588
  3. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,913
    Here's a thread on that: https://forum.unity.com/threads/i-f...using-inverselerp-whenever-i-use-lerp.834997/

    The first post is from someone using inverselerp (to get the percent -- your first line) followed by lerp (your second line). Then there are several people playing with custom rescale function (which is just what you write, as a function). Basically, the thread beats to death that you can make it look different, but there's no obvious better way.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,560
    Your code is great!

    My only quibble is that you're doing everything with an inverted percent.

    The math works out obviously, but to me a
    percent
    should be 0.0 at min and 1.0 at max

    Yours is exactly the opposite. If you doubt me, print out the value of
    percent
    and see.

    Personally, I would write it as:

    Code (csharp):
    1.     float AdjustedProportion(float input)
    2.     {
    3.         //Convert to percent of first range
    4.         float percent = (input - minA) / (maxA - minA);
    5.  
    6.         //Convert back to number within second range
    7.         return minB + percent * (maxB - minB);
    8.     }
    That way if you ever have to debug it the numbers aren't
    1.0f - percent,
    they're "just"
    percent
    .
     
    Sluggy likes this.