-- Tick工具,可用于简化一些需要临时tick的逻辑 GlobalTickTool = GlobalTickTool or {}; GlobalTickTool.Functions = {}; GlobalTickTool.Functions1s = {}; GlobalTickTool.CustomTicks = {}; GlobalTickTool.InternalTicks = {}; --- 注册tick回调函数 ---@generic T ---@param o T ---@param f fun(o:T, dt: float, st: float) tick 函数 ---@param ef fun(o:T): bool 是否要执行 tick ---@param l float 限制到什么时候 function GlobalTickTool:AddTick(o, f, ef, l) if o == nil then return; end if GlobalTickTool.Functions[o] ~= nil then return; end if type(f) ~= "function" then return; end GlobalTickTool.Functions[o] = { f = f, e = ef, s = 0, l = l }; end --- 添加间隔执行,执行多少次的逻辑 ---@generic T ---@param o T ---@param f fun(o:T, dt: float, st: float, t:int32) tick 函数 ---@param i float 每次间隔时间 ---@param c int32 执行次数 ---@param l fun(o: T) 结束的时候执行的函数 ---@param inf fun(o:T):bool 打断函数 function GlobalTickTool:AddInternalCount(o, f, i, c, l, inf) if o == nil then return; end if GlobalTickTool.InternalTicks[o] ~= nil then return; end if type(f) ~= "function" then return; end if type(inf) ~= 'function' then inf = nil end if type(l) ~= 'function' then l = nil end if i <= 0 then i = 0 end GlobalTickTool.InternalTicks[o] = { f = f, s = 0, i = i, c = c, inf = inf, l = l, } end --- 改变执行次数 function GlobalTickTool:UpdateInternalCount(o, c) if o == nil then return end if GlobalTickTool.InternalTicks[o] == nil then return; end GlobalTickTool.InternalTicks[o].c = c; end function GlobalTickTool:GetInternalCount(o) return GlobalTickTool.InternalTicks[o].c; end --- 注销tick回调函数 ---@param o UObject function GlobalTickTool:RemoveTick(o) if GlobalTickTool.Functions ~= nil then GlobalTickTool.Functions[o] = nil; end end function GlobalTickTool:RemoveCustomTick(o) if GlobalTickTool.CustomTicks ~= nil then GlobalTickTool.CustomTicks[o] = nil; end UGCLogSystem.LogTree(string.format("[GlobalTickTool:RemoveCustomTick] GlobalTickTool.CustomTicks ="), GlobalTickTool.CustomTicks) end --- 调用所有注册的回调函数,此函数需要在gamestate的tick里调用一下 ---@param dt float ---@param ServerTime float function GlobalTickTool:ReceiveTick(dt, ServerTime) for o, t in pairs(self.Functions) do if t.e == nil or t.e(o) then t.s = t.s + dt; t.f(o, dt, ServerTime); if t.l ~= nil and t.s > t.l then GlobalTickTool:RemoveTick(o); end end end --for o, t in pairs(self.Functions1s) do -- if t.e == nil or t.e(o) then -- if (t.t ~= nil and ServerTime - t.t >= 1) or (t.t == nil) then -- t.t = ServerTime; -- t.f(o, dt, ServerTime); -- end -- end --end --- { f = f, c = t, s = 0, } for o, t in pairs(self.CustomTicks) do t.s = t.s + dt; if t.s >= t.c then t.s = t.s - t.c; t.f(o, dt, ServerTime); end end for o, t in pairs(self.InternalTicks) do t.s = t.s + dt; if t.s >= t.i and t.i > 0 then t.s = t.s - t.i; t.c = t.c - 1; t.f(o, dt, ServerTime, t.c); if (t.c == 0) or (t.inf ~= nil and t.inf(o)) then -- 移除 GlobalTickTool.InternalTicks[o] = nil; if t.l ~= nil then t.l(o); end end end end end return GlobalTickTool