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

Convert any value to Percentage

Discussion in 'Scripting' started by WanAmir, Apr 21, 2021.

  1. WanAmir

    WanAmir

    Joined:
    Jul 17, 2018
    Posts:
    27
    Hi everyone!
    I want to make a radial progress bar using sprite renderer instead of UI image.
    And I found this shader on the internet, the float value called Pie Angle goes from 0 to 360. [0=Fill, 360=Not fill]
    Screenshot_1.png

    And I have a float variable called Calories goes from 0 to Max.
    So how do I match the Calories value with the Pie Angle or vice versa?
    My idea is to convert both values become 0 to 1 but I don't know how to do it or is there any better way to do it?

    Thank you in advance :)
     
  2. TheNightglow

    TheNightglow

    Joined:
    Oct 1, 2018
    Posts:
    201
    to convert a value in the range 0-Max to the range 0-1 just devide the value by Max

    as in PieAngle / 360
    and Calories / MaxCalories

    Edit:
    and for completeness sake, to convert a value from range Min-Max to 0-1, you would substact Min and than devide by Max - Min
    as in:
    p = (x - Min) / (Max-Min)
     
    Joe-Censored and WanAmir like this.
  3. WanAmir

    WanAmir

    Joined:
    Jul 17, 2018
    Posts:
    27
    Thank you for the answer. Really appreciate it
    So I've created these values for testing and it works...but how do I link those 2 values?
    For example:
    When I feed 400 calories into CurrentCalories, the PercentCalories shows 0.5 which is perfect but how do link to the PercentRadial to be 0.5 too?
    Screenshot_2.png
    Screenshot_3.png


    note: sorry for the dumb question.
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
  5. WanAmir

    WanAmir

    Joined:
    Jul 17, 2018
    Posts:
    27
    YES. This is what I actually want. TIL new word: Remap
    I put the code for reference.
    Code (CSharp):
    1.  public static float Remap (this float from, float fromMin, float fromMax, float toMin,  float toMax)
    2.     {
    3.         var fromAbs  =  from - fromMin;
    4.         var fromMaxAbs = fromMax - fromMin;    
    5.      
    6.         var normal = fromAbs / fromMaxAbs;
    7.         var toMaxAbs = toMax - toMin;
    8.         var toAbs = toMaxAbs * normal;
    9.         var to = toAbs + toMin;
    10.      
    11.         return to;
    12.     }
    code.png
    On line 61, I swap the minRadial and maxRadial because the value in shader is reverse (min=Fill, max=Empty).
    If the radial is not reverse (min=Empty, max=Fill) just put the min value first then max after that.

    The result:
    Screenshot_4.png

    Thank you for the answers. My problem is solved for now. :)