sonic-bluestreak/sonic-radiance.love/core/modules/assets/animator.lua
2019-02-03 19:40:28 +01:00

87 lines
2.6 KiB
Lua

-- assets/animator :: the animator object. The animator object handle what
-- frame a sprite should draw.
--[[
Copyright © 2019 Kazhnuz
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
local Animator = Object:extend()
function Animator:new(sprite)
self.sprite = sprite
self.frame = 1
self.frameTimer = 0
self.currentAnimation = ""
self.animationData = {}
self.customSpeed = 0
self:changeToDefaultAnimation()
end
function Animator:setCustomSpeed(customSpeed)
self.customSpeed = customSpeed or 0
end
function Animator:update(dt)
if (self.currentAnimation == "") then
print("warning: no current animation data")
return 0
end
local speed = self.animationData.speed
if (self.animationData.speed) == -1 then
speed = self.customSpeed --math.abs(self.xsp / 16)
end
self.frameTimer = self.frameTimer + (speed * dt)
if self.frameTimer > 1 then
self.frameTimer = 0
if self.frame == self.animationData.endAt then
self.frame = self.animationData.loop
else
self.frame = self.frame + 1
end
end
end
function Animator:getFrame()
return self.frame
end
function Animator:draw(x, y, r, sx, sy, ox, oy, kx, ky)
self.sprite:drawFrame(self.frame, x, y, r, sx, sy, ox, oy, kx, ky)
end
function Animator:changeAnimation(name, restart)
self.currentAnimation = name
self.animationData = self.sprite.data.animations[self.currentAnimation]
local restart = restart or true
if (restart) then
self.frame = self.animationData.startAt
self.frameTimer = 0
end
end
function Animator:changeToDefaultAnimation(restart)
self:changeAnimation(self.sprite.data.metadata.defaultAnim, restart)
end
return Animator