Hey @professir! Good one. In that vein, here are some functions I use that are complementary to the one you shared:
-- Get a version of val that does not spill outside of min and max.
-- Example: clamp(1.5, -1.1, 1.1) returns 1.1
function clamp(val, min, max)
return val < min and min or val > max and max or val
end
-- Find number between two numbers (a, b) at t [0, 1]
-- Example: lerp(10, 30, 0.5) returns 20 (halfway between 10 and 30).
function lerp(a, b, t)
return math.ceil(a * (1 - t) + b * t)
end
-- Find value [0, 1] between two numbers (a, b) at v
-- Example: invlerp(10, 30, 20) returns 0.5
function invlerp(a, b, v)
return clamp((v - a) / (b - a), 0, 1)
end
-- Finds value [0, 1] of input between output.
-- Example: remap(20, 10, 30, 30, 50) returns 40 as 20 is halfway between 10 and 30 and remapped to new range 30 to 50 is 40. This function allows you to remap a value between two ranges.
function remap(input_val, input_min, input_max, output_min, output_max)
return lerp(output_min, output_max, invlerp(input_min, input_max, input_val))
end