GDScript math challenge, how to do inversely proportional quantities?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By The_Black_Chess_King

How we link two numerical variables together with inversely proportional quantities?

Same in math, when SPEED goes up, TIME to reach destination shortens.

The application would be a Lens Flare Sprite fading from the camera, the idea is to decrease visibility based on distance from the camera.

I could manually do:

match Distance:
     10: set_modulate(Color(1,1,1,1.0))
     20: set_modulate(Color(1,1,1,0.9))
     30: set_modulate(Color(1,1,1,0.8))
     40: set_modulate(Color(1,1,1,0.7))
     50: set_modulate(Color(1,1,1,0.6))
     60: set_modulate(Color(1,1,1,0.5))

But heck no, that’s a retrocess.

I’m sure there’s a solution, and this question could be applied to multiple different cases.

:bust_in_silhouette: Reply From: i_love_godot

I’m not familiar with how lens flares work, but is it possible to calculate the range of the flare distances? A minimum and maximum distance from the camera, then you could convert that into a float between 0 and 1 that you could simply plug into the modulate.

It was just a sprite, and I was using distance_to to the camera2d.

The_Black_Chess_King | 2020-01-20 16:01

:bust_in_silhouette: Reply From: jgodfrey

It looks like you want to map a number in one range to a number in a different range. That’s exactly what range_lerp does. For the above example, something like the below should do what you want…

Basically, this maps a number in the range of 10 to 100 to a number in the range of 1 to 0.1

Using your above Distance variable, this should map to the correct output value.

var mappedVal = range_lerp(Distance, 10, 100, 1, .1)