• # Inverse Lerp - a super useful yet often overlooked function

General and Gameplay Programming

Lerp( a, b, t ) = value
InvLerp( a, b, value ) = t

• lerp returns a blend between a and b, based on a fraction t
• inverse lerp returns a fraction t, based on a value between a and b

Use case! 🔊

Say you want to control audio source volume based on distance

• at 10 meters, you want volume 1
• at 20 meters, you want volume 0

Then the volume is then given by

volume = InvLerp( 20, 10, distance )

If you've ever used photoshop's levels tool, then you've used both lerp and inverse lerp! 🎨

The input values use inverse lerp, the output values use lerp!

When used with images, inverse lerp can be used to increase value contrast! for example, here's a selfie before and after an inverse lerp💖

Also, note that some Lerp/InvLerp functions also extrapolate (such as in shaders), while others clamp the values within your given range (such as Unity's Mathf.Lerp/InverseLerp functions)

Make sure you clamp unless you want to extrapolate 📈

Here's an interesting use case!

An inv lerp where a and b are colors and the value parameter is the depth of this water, you can achieve hue-shifting for a color elimination effect by depth🌊

Addendum - another useful function is Remap!

Remap takes a value within a given input range into a given output range, which is basically a combined inverse lerp and lerp!

Here's the code for all three!

(Also, none of these are clamped - they can all extrapolate)

Enjoyed this quick lesson?  Check out Freya's work via the following social platforms:

💖 Patreon ❱ https://patreon.com/acegikmo
📺 Twitch ❱ https://twitch.tv/acegikmo
💬 Discord ❱ https://discord.gg/v5VWuga
🌸 Instagram ❱ https://instagram.com/freya_holmer

Further reading on GameDev.net: A Brief Introduction to Lerp, by Matt DesLauriers

Report Article

## User Feedback

Discovered I was calling it Unlerp in my code, think your name is better. Nice post

## Create an account

Register a new account

• 0
• 0
• 2
• 0
• 4

• 9
• 56
• 18
• ### Similar Content

• Hello Forum,
I reached a point in my rework of our build tool where I have to improve parsing different coding languages like C# and C++ to detect dependencies between files and projects. Maybe I will also add some kind of linting to the build tool. Unfortunately I'm fixed to an older version of C# to stay backwards compatible to older Visual Studio versions. This is the reason for not having the chance to use the Roslyn parser framework out of the box and I had to write my own "analyzer" to solve the task.
That I'm now ready for refactoring, I want to make it into a real parser instead of Regex driven analyzer. For this task, I also had a look at parser utility libraries like Sprache and Pidgin to have some more convinience in declaring tokens and rules. I have written parsers on my own by hand many times before and they were always optimized to the special token/ rule and usecase. For example instead of just reading the next string and then comparing it to a keyword, then conditionally reset the stream or pass the token, I wrote something like this
char[] buffer = new buffer[<max keyword length>]; bool MyKeywordRule(Stream data, TokenStream result) { if(data.Peek() != myKeywordFirstChar) return false; long cursor = data.Position; int count = data.Read(buffer, 0, Math.Min(myKeywordLength, data.Length - cursor)); if(count == myKeywordLength && buffer.Compare("keyword", myKeywordLength)) { result.Add(myToken); return true; } else { data.Position = cursor; return false; } } My hand written function is optimized in performance to first test the character, then fill a buffer with data that is as long as the keyword and finally test this for equality with the keyword. If I write this in Sprache or Pidgen, it will just read the stream, compare the result for the keyword and reset on failure, no early out will be performed or whatever speed optimization. If I want to test against a range of keywords or character sequences like for operators, in a generic solution it will read every statement of the sequence from the stream and test it while my hand written solution can fill the buffer once and test the result in a switch statement and early outs for the character count read.
My question is if there exists a solution that can perform both, define rules in a convinient way like Sprache or Pidgin and on the other hand compete somehow with a hand written solution (it must not be as fast but in any way faster than simply replay the parts of a rule). I thought about a solution using C# Expressions where an operation for example my keyword, can be written as a sequence of pre-condition (testing the character), bootstrapping (reading the buffer for certain size) and validation (test if the buffer matches the keyword) and be merged together for example, so that a rule "A or B" dosen't test for a first then resets the stream and tests for B second but merges the pre-condition into

IF not('A') and not('B') FAIL fills the buffer only once and then tests for equality in a switch-case statement. Or is it the best solution to keep writing such code by hand for each individual rule?
• By rogerdv
Im trying to create a system to keep the states of the scenes in an RPG, and my first approach was to have all entities (NPCs, containers, etc) of non active scene in memory, to restore them when its scene gets loaded again. But somebody told me that such idea was not optimal, because of memory consumption, and that the best way was to serialize the scene state to disk when exiting, and restoring from disk when loading again. But that gives me some doubts, because it would require an intensive use of disk (consuming SSD write cycles) and arises the problem of what to do with saved scene states when exiting the game: keep them and reference thos files from global savegame archive (with all possible derived problems), or delete them and saving the state to the saved game. Whats the best choice in this case? I have been looking at the savegames of AAA games and none of them seems to keep any serialized scenes outside the main saved game file.
• By Stocke
I looked into flow field pathfinding(after reading about steering behaviours) and it seems that it's mostly used for RTS games. I understand why, but wouldn't it also work for an action game with a single player character? It wouldn't be efficient, sure but it makes using steering behaviours easier to use. I could precalculate obstacles based on static colliders in the scene. And I can calculate the a vector towards the player for seek behaviours every frame. And reuse that for every enemy.
I could then use inverse of the vectors for flee behaviours and make that avoid obstacles as well.
If I wanted to steer a character perpendicular to the player, maybe I could rotate the vector in the field 90 degrees to obtain that?
Of course this approach would not be valid for other behaviours. Like for pursuit you would need to calculate another vector field for the future position of the player. Unless there is some mathematical way to shift a flow field if the center(where the arrows converge) moves.
I dunno how you would add local avoidance. Maybe keep track of enemy positions on another vector field and take that into consideration.
A* is no doubt efficient and popular. But it does not work well if the agent has target velocities instead of target positions (like from using steering behaviours). And A* also has the problem of being too good(perfect paths => too robotic).
Anyways, that's enough rambling from me. What do you think?
• By Stocke
I am trying to implement obstacle avoidance in unity as follows: I fire a series of parallel raycasts in the players moving direction, get the closest hit and then multiply hit.normal by steering force to get an avoidance vector.Then I use prioritization blending(have some max steering, I add obstacle avoidance steering first and then add seek steering towards target if I have not already reached max steering). The problem is that If the player is directly behind the wall then the seek direction and hit.normal(aka avoidance direction) is in opposite. Hit. normal seems to work if obstacle is far away but not much so if the obstacle is near. Am I supposed to calculate some other way?(normal component of hit.normal on my velocity vector maybe).
And is it better to have  cone raycasts instead of parallel ones?

• Hello! I'm in the middle of a procedural texture system (for things like lightmaps, splatoon-style decal painting etc.) and I have an annoying artefact I don't seem to be able to get rid of.
I've been working through this ( https://www.flipcode.com/archives/Lightmap_Storage.shtml ) method of generating atlas uvs, which mostly works pretty well (here on a capsule):

But under closer inspection has artefacts around the places where the charts meet:

Since this method of uv generation splits tris into charts based on  primary axis, this is where the charts join up. I've drawn out roughly the edges of the three visible charts and you can see how it lines up:

I've got the texture filtering set to 'point' for debugging.
So from what I can see the uvs are correct and the texel edges are all aligned correctly, it's just that the fringe texels from one atlas don't match their counterpart texels in the other charts. I'm calling these 'twinned' texels - they exist twice (or more) in the atlas texture, but to eliminate these artifacts they should be identical colours.

To populate the texture I've got an unwrapped version of the mesh (which basically swaps vertex positions with uvs) which can be rendered into the texture directly. My thinking was that if I divide the world into a 3d grid and have the shader's output colour *only* dependant on the grid position (not the actual fragment world position) then these 'twinned' texels would evaluate to the same colour in all instances, even though it was being generated by different  geometry. Although clearly something's not working.
Shader "Unlit/Atlas" { Properties { _MainTex ("Texture", 2D) = "white" {} _VoxelSize("Voxel Size", Float) = 1.0 _ColourScale("Colour Scale", Float) = 0.1 _ColourOffset("Colour Offset", Vector) = (0,0,0,0) } SubShader { Tags { "RenderType"="Opaque" } Cull Off ZWrite Off ZTest Off LOD 100 Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" struct appdata { float4 vertex : POSITION; float2 uv0 : TEXCOORD0; float2 uv1 : TEXCOORD1; }; struct v2f { float2 uv0 : TEXCOORD0; float2 uv1 : TEXCOORD1; float2 atlasCoord : TEXCOORD2; float4 vertex : SV_POSITION; }; sampler2D _MainTex; float4 _MainTex_ST; float _VoxelSize; float _ColourScale; float4 _ColourOffset; v2f vert (appdata v) { v2f o; o.vertex = UnityObjectToClipPos(v.vertex); o.uv0 = v.uv0; o.uv1 = v.uv1; o.atlasCoord = v.vertex.xy; return o; } fixed4 frag (v2f i) : SV_Target { fixed4 col = fixed4(0.0, 0.0, 0.0, 1.0); // Extract model's world space coord from two uv channels float3 worldCoord = float3(i.uv0.xy, i.uv1.x); // World coords (in meters) // Snap from world space to containing voxel coord float3 voxelCoord = floor(floor(worldCoord / _VoxelSize)); // Voxel coords (integer values) // Convert voxel xyz into colour range col.xyz = frac((voxelCoord * _ColourScale) + _ColourOffset.xyz); return col; } ENDCG } } } One thing I'm not sure of the proper solution to is making sure all the atlas  texels actually get rendered to. If I just draw the unwrapped tris directly then they don't always touch all the texels they need to around the edges:

So I'm manually extending the edges of the charts with additional fins to make sure these are filled in:

This seems more accurate than just running a 2d dilate operation (since it should go through the deterministic grid method) but maybe I'm missing something. Has anyone any ideas where these artefacts might be coming from and how to make sure these 'twinned' texels are rendered out correctly? Even if I wanted to fudge it in a post-process, I'm drawing a blank as to how to actually figure out which texels would need to be processed this way.
Thanks.
×