Search Unity

  1. Unity 2019.1 is now released.
    Dismiss Notice

Remap range of numbers to 0 to 1

Discussion in 'Scripting' started by crawl55, Dec 9, 2018.

  1. crawl55

    crawl55

    Joined:
    Jan 17, 2014
    Posts:
    8
    My overall objective is to take a heading range(0° to 360°, remap it to a range of 0 to 1, and send that value to a separate function to force a specific frame of an animation to play.

    I have done several searches, and found several different applications ranging from normalize to lerp, but I think I may have confused myself. Any help would be appreciated!
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    6,354
    So the simple solution is to just divide by the max value of 360. This works because your min is 0.

    x/360 = percentage

    If the range wasn't 0->m, but instead n->m. You'd need to subtract the min, and divide by the range (it's literally the inverse of lerp).

    (x - n) / (m - n) = percentage

    You can see if you substitute 0 in for n, you get the x / m for the previous.

    And lets say you needed to map it to a range of a -> b, you can take that 0->1 and multiply it by said range using lerp.

    ((x - n) / (m - n)) * (b - a) + a

    you could see this as f(g(x)) where g(x) is the inverse lerp, and f(x) is lerp.

    g(x) = (x-n) / (m-n)
    f(x) = x * (b - a) + a

    replace f(g(x)) = g(x) * (b - a) + a
     
  3. crawl55

    crawl55

    Joined:
    Jan 17, 2014
    Posts:
    8
    It was right in front of my face. Thank you for the response.