summaryrefslogtreecommitdiff
path: root/animation.lua
diff options
context:
space:
mode:
Diffstat (limited to 'animation.lua')
-rw-r--r--animation.lua68
1 files changed, 68 insertions, 0 deletions
diff --git a/animation.lua b/animation.lua
new file mode 100644
index 0000000..7d77d40
--- /dev/null
+++ b/animation.lua
@@ -0,0 +1,68 @@
+local Animation = {}
+Animation.__index = Animation
+
+function Animation.new(imageOrPath, width, height, duration)
+ local self = setmetatable({}, Animation)
+
+ if type(imageOrPath) == "string" then
+ self.spriteSheet = love.graphics.newImage(imageOrPath)
+ else
+ self.spriteSheet = imageOrPath
+ end
+
+ self.frameWidth = width
+ self.frameHeight = height
+ self.quads = {}
+
+ local imgW, imgH = self.spriteSheet:getDimensions()
+ for y = 0, imgH - height, height do
+ for x = 0, imgW - width, width do
+ table.insert(self.quads, love.graphics.newQuad(x, y, width, height, imgW, imgH))
+ end
+ end
+
+ self.duration = duration or 1
+ self.currentTime = 0
+
+ return self
+end
+
+function Animation:update(dt)
+ self.currentTime = self.currentTime + dt
+ if self.looping == false then
+ if self.currentTime > self.duration then
+ self.currentTime = self.duration
+ end
+ else
+ if self.currentTime >= self.duration then
+ self.currentTime = self.currentTime % self.duration
+ end
+ end
+end
+
+function Animation:reset()
+ self.currentTime = 0
+end
+
+-- Returns true only for non-looping animations that have played through once.
+function Animation:isFinished()
+ return self.looping == false and self.currentTime >= self.duration
+end
+
+function Animation:draw(x, y, flipHorizontal)
+ if #self.quads == 0 then return end
+
+ local t = self.currentTime / self.duration
+ local index = math.floor(t * #self.quads) + 1
+ if index > #self.quads then index = #self.quads end
+
+ local quad = self.quads[index]
+ local sx = (flipHorizontal and -1) or 1
+ local sy = 1
+ local ox = flipHorizontal and self.frameWidth or 0
+ local oy = 0
+
+ love.graphics.draw(self.spriteSheet, quad, x, y, 0, sx, sy, ox, oy)
+end
+
+return Animation