From a0ba6f9da3e09c1a65154201cc15475fe173b029 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lera=20Elvo=C3=A9?= Date: Fri, 14 Feb 2025 22:02:19 +0300 Subject: [PATCH] add lerp function to util and lerp method to vector3 --- data/scripts/types/vector3.lua | 19 +++++++++++++++++++ data/scripts/util.lua | 20 ++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/data/scripts/types/vector3.lua b/data/scripts/types/vector3.lua index 893313a..5c08f53 100644 --- a/data/scripts/types/vector3.lua +++ b/data/scripts/types/vector3.lua @@ -216,6 +216,25 @@ end function Vector3:copy() return Vector3(self) end + +---Returns a new vector as a linear interpolation between self and b. +---@param b vectorlike +---@param t number +---@return Vector3 +function Vector3:lerp(b, t) + -- return self:copy() + if not is_weak_vector3(b) then + error("Vector3: b must be a Vector3-like table. Returning copy of self.") + return self:copy() + end + local w = Vector3(b) + return Vector3{ + util.lerp(self.x, w.x, t), + util.lerp(self.y, w.y, t), + util.lerp(self.z, w.z, t), + } +end + ---- CONSTANTS Vector3.UP = Vector3(0, 1, 0) diff --git a/data/scripts/util.lua b/data/scripts/util.lua index 8329323..1cad958 100644 --- a/data/scripts/util.lua +++ b/data/scripts/util.lua @@ -97,4 +97,24 @@ function util.list_insert_once(t, value) if util.list_find(t, value) ~= -1 then return end table.insert(t, value) end + +---linear interpolation +---@param a number +---@param b number +---@param t number in [0, 1] +---@return number +function util.lerp(a, b, t) + return a + t * (b - a) +end + +---constrains v between min and max +---@param v number +---@param min number +---@param max number +---@return number +function util.clamp(v, min, max) + return math.max(math.min(v, max), min) +end + + return util \ No newline at end of file