ExperimentalGear/scripts/core/math.lua

51 lines
1015 B
Lua

---Clamp value between minimum and maximum
---@param x number
---@param min number
---@param max number
---@return number
function math.clamp(x, min, max)
if x < min then
x = min
end
if x > max then
x = max
end
return x
end
---Return closest numerical value to number
---@param num number
---@return integer
---@note From https://stackoverflow.com/a/76576968
function math.round(num)
return math.floor((math.floor(num*2) + 1)/2)
end
---Return sign of number
---@param x number
---@return integer
function math.sign(x)
if (x > 0) then
return 1
end
if (x < 0) then
return -1
end
return 0
end
---Linear interpolation
---@param x number # x to interpolate
---@param x0 number # x value begin
---@param x1 number # x value end
---@param y0 number # y value at x0
---@param y1 number # y value at x1
---@return number # interpolated y value at x
function math.lerp(x, x0, x1, y0, y1)
return y0 + (x - x0) * (y1 - y0) / (x1 - x0)
end