This repository has been archived on 2022-10-27. You can view files and clone it, but cannot push or open issues or pull requests.
InfinitShoot/game/animation.lua

84 lines
1.7 KiB
Lua
Raw Permalink Normal View History

2022-08-02 19:29:44 +08:00
local hazel = require "hazel"
---@class Animation
local _M = {}
---@class Frame
---@field row number
---@field col number
---@field time number
2022-08-04 00:14:17 +08:00
---@param tilesheet TileSheet
2022-08-02 19:29:44 +08:00
---@param frames table<Frame>
2022-08-02 21:58:27 +08:00
---@param onEndCallback function
function _M.CreateAnimation(tilesheet, frames, onEndCallback)
local o = {tilesheet = tilesheet, frames = frames, index = 1, counter = 0, isPlaying = false, onEndCallback = onEndCallback}
2022-08-02 19:29:44 +08:00
setmetatable(o, {__index = _M})
return o
end
---@param self Animation
function _M.Play(self)
self.isPlaying = true
end
---@param self Animation
function _M.Stop(self)
self.isPlaying = false
self.index = 1
self.counter = 0
end
---@param self Animation
function _M.Pause(self)
self.isPlaying = false
end
function _M.GetCurFrame(self)
if self.index > #self.frames then
return self.frames[#self.frames]
else
return self.frames[self.index]
end
end
2022-08-04 00:14:17 +08:00
---@return TileSheet
---@param self Animation
2022-08-02 19:29:44 +08:00
function _M.GetTilesheet(self)
return self.tilesheet
end
---@param self Animation
function _M.Rewind(self)
2022-08-02 21:58:27 +08:00
self.index = 1
2022-08-02 19:29:44 +08:00
self.counter = 0
end
---@param self Animation
function _M.IsPlaying(self)
return self.isPlaying
end
---@param self Animation
function _M.Update(self)
if not self.frames or not self:IsPlaying() then
return
end
if self.index > #self.frames then
self:Pause()
2022-08-02 21:58:27 +08:00
if self.onEndCallback then
self.onEndCallback(self)
end
return
2022-08-02 19:29:44 +08:00
end
self.counter = self.counter + hazel.Time.GetElapseTime()
---@type Frame
local curFrame = self.frames[self.index]
if self.counter >= curFrame.time then
self.counter = self.counter - curFrame.time
self.index = self.index + 1
end
end
return _M