69 lines
2.5 KiB
Lua
69 lines
2.5 KiB
Lua
local utils = require "lib.utils.utils"
|
|
|
|
--- @alias State "idle"|"run"|"attack"|"hurt"
|
|
|
|
--- @class Logic
|
|
--- @field id Id
|
|
--- @field mapLogic MapLogic
|
|
--- @field state State
|
|
local logic = {}
|
|
logic.__index = logic
|
|
|
|
--- @param id Id
|
|
--- @param position? Vec3
|
|
--- @param size? Vec3
|
|
local function new(id, position, size)
|
|
return setmetatable({
|
|
id = id,
|
|
mapLogic = (require 'lib.character.map_logic').new(id, position, size),
|
|
state = "idle"
|
|
}, logic)
|
|
end
|
|
|
|
--- @param path Deque
|
|
function logic:followPath(path)
|
|
if path:is_empty() then return end
|
|
self.mapLogic.path = path;
|
|
---@type Vec3
|
|
local nextCell = path:peek_front()
|
|
self:runTo(nextCell)
|
|
path:pop_front()
|
|
end
|
|
|
|
--- @param target Vec3
|
|
function logic:runTo(target)
|
|
self.mapLogic.t0 = love.timer.getTime()
|
|
self.state = "run"
|
|
self.mapLogic.runTarget = target
|
|
local charPos = self.mapLogic.position
|
|
if target.x < charPos.x then
|
|
Tree.level.characters[self.id].graphics.animation.side = LEFT
|
|
elseif target.x > charPos.x then
|
|
Tree.level.characters[self.id].graphics.animation.side = RIGHT
|
|
end
|
|
end
|
|
|
|
function logic:update(dt)
|
|
if self.state == "run" and self.mapLogic.runTarget then
|
|
local delta = love.timer.getTime() - self.mapLogic.t0 or love.timer.getTime()
|
|
local fraction = delta /
|
|
(0.5 * self.mapLogic.runTarget:subtract(self.mapLogic.position):length()) -- бежим одну клетку за 500 мс, по диагонали больше
|
|
if fraction >= 1 then -- анимация перемещена завершена
|
|
self.mapLogic.position = self.mapLogic.runTarget
|
|
if not self.mapLogic.path:is_empty() then -- еще есть, куда бежать
|
|
self:runTo(self.mapLogic.path:peek_front())
|
|
self.mapLogic.path:pop_front()
|
|
else -- мы добежали до финальной цели
|
|
self.state = "idle"
|
|
self.mapLogic.runTarget = nil
|
|
end
|
|
else -- анимация перемещения не завершена
|
|
self.mapLogic.displayedPosition = utils.lerp(self.mapLogic.position, self.mapLogic.runTarget, fraction) -- линейный интерполятор
|
|
end
|
|
end
|
|
|
|
Tree.level.characterGrid:add(self.id)
|
|
end
|
|
|
|
return { new = new }
|