Last active
February 26, 2021 17:27
-
-
Save Vavassor/57d8b635676429a58eb58bb34c28b460 to your computer and use it in GitHub Desktop.
Linear Interpolation
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
| /** | |
| * Linearly interpolate, or produce a point that is a given fraction of the way | |
| * between two other points. | |
| * | |
| * This is equivalent to the weighted arithmetic mean of the two points, | |
| * where t is the weight. | |
| * | |
| * @param {number} v0 the starting bound, returned when t=0 | |
| * @param {number} v1 the ending bound, returned when t=1 | |
| * @param {number} t the fraction between the given data points, also called the interpolant | |
| * @returns a number that is some fraction t between the values v0 and v1 | |
| */ | |
| export function lerp(v0, v1, t) { | |
| return (1 - t) * v0 + t * v1; | |
| } | |
| /** | |
| * Linearly map a data point in one interval to the corresponding place in | |
| * another interval. | |
| * | |
| * For example, suppose there's a volume slider control and the goal is to | |
| * determine the current volume level from the position of the slider. It has a | |
| * track that's 128 pixels long and the slider is currently at a position 24 | |
| * pixels from the start. So, 24 is in the range of 0 to 128. Determining the | |
| * volume level from 0 to 100 would be the result from | |
| * linearRemap(0, 128, 0, 100, 24). This is a volume level of 18.75. | |
| * | |
| * @param {number} xMin the lower bound of the starting interval | |
| * @param {number} xMax the upper bound of the starting interval | |
| * @param {number} yMin the lower bound of the ending interval | |
| * @param {number} yMax the upper bound of the ending interval | |
| * @param {number} x the value in the starting interval | |
| * @returns a value "y" in the ending interval | |
| */ | |
| export function linearRemap(xMin, xMax, yMin, yMax, x) { | |
| return lerp(yMin, yMax, unlerp(xMin, xMax, x)); | |
| } | |
| /** | |
| * The inverse of lerp. Determine the fraction of the way along an interval that | |
| * a given point is. | |
| * | |
| * @param {number} v0 the start value | |
| * @param {number} v1 the end value | |
| * @param {number} x the value between v0 and v1 | |
| * @returns a fraction representing how far between v0 and v1 a given point x is | |
| */ | |
| export function unlerp(v0, v1, x) { | |
| return (x - v0) / (v1 - v0); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment