Created
July 5, 2022 11:36
-
-
Save mimshins/04ed97a1c6301f248b23509a1be731b5 to your computer and use it in GitHub Desktop.
Lerp (linear interpolation), InverseLerp, and Remap functions in TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Linear interpolate on the scale given by `a` to `b`, using `t` as the point on that scale. | |
*/ | |
export const lerp = (a: number, b: number, t: number) => a + t * (b - a); | |
/** | |
* Inverse Linar Interpolation, get the fraction between `a` and `b` on which `v` resides. | |
*/ | |
export const inLerp = (a: number, b: number, v: number) => (v - a) / (b - a); | |
/** | |
* Remap values from one linear scale to another. | |
* | |
* `oMin` and `oMax` are the scale on which the original value resides, | |
* `rMin` and `rMax` are the scale to which it should be mapped. | |
*/ | |
export const remap = ( | |
v: number, | |
oMin: number, | |
oMax: number, | |
rMin: number, | |
rMax: number | |
) => lerp(rMin, rMax, inLerp(oMin, oMax, v)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment