Scalar

Number helpers for animation code: lerp, inverseLerp, clamp, wrap, remap, damp and snap. Plain functions on numbers, with no services, so they work anywhere, a frame's step included.

import * as Scalar from "@wardic/core/Scalar"

const scale = Scalar.remap(scrollY, 0, 400, 1, 0.6) // a header that shrinks as you scroll

Functions

clamp()

function clamp(
   value, 
   min, 
   max
): number;

value kept within min and max, both included: clamp(120, 0, 100) is 100.

Parameters

value

number

min

number

max

number

Returns

number


damp()

function damp(
   current, 
   target, 
   lambda, 
   dt
): number;

One frame's step of a value easing toward target, the same at any frame rate: it moves 1 − e^(−lambda · dt) of the way. lambda is how fast, per second; dt is the frame's seconds.

Parameters

current

number

target

number

lambda

number

dt

number

Returns

number

Example

x = Scalar.damp(x, pointerX, 12, dt) // each frame: x trails the pointer

inverseLerp()

function inverseLerp(
   a, 
   b, 
   value
): number;

How far value is from a to b, as a fraction: inverseLerp(0, 100, 25) is 0.25, the inverse of lerp. 0 when a and b are the same.

Parameters

a

number

b

number

value

number

Returns

number


lerp()

function lerp(
   a, 
   b, 
   t
): number;

The point t of the way from a to b: lerp(0, 100, 0.25) is 25. t isn't clamped, so 1.5 goes half as far again past b.

Parameters

a

number

b

number

t

number

Returns

number

Example

const x = Scalar.lerp(from, to, progress)

remap()

function remap(
   value, 
   inMin, 
   inMax, 
   outMin, 
   outMax
): number;

value moved from one range onto another: remap(50, 0, 100, 0, 1) is 0.5. It isn't clamped, so a value outside the first range lands outside the second; clamp the result to keep it in.

Parameters

value

number

inMin

number

inMax

number

outMin

number

outMax

number

Returns

number


snap()

function snap(value, step): number;

value rounded to the nearest multiple of step: snap(47, 10) is 50. A step of 0 leaves it as it is.

Parameters

value

number

step

number

Returns

number


snapTo()

function snapTo(value, points): number;

The entry of points nearest value: snapTo(130, [0, 100, 250]) is 100. value itself when points is empty.

Parameters

value

number

points

readonly number[]

Returns

number


wrap()

function wrap(
   value, 
   min, 
   max
): number;

value wrapped round into min to max, as an angle wraps: wrap(7, 0, 5) is 2, wrap(-1, 0, 5) is 4. max itself wraps to min.

Parameters

value

number

min

number

max

number

Returns

number