diff options
| author | cursed22bc <admin@pixeldawn.org> | 2026-03-01 12:30:05 +0200 |
|---|---|---|
| committer | cursed22bc <admin@pixeldawn.org> | 2026-03-01 12:30:05 +0200 |
| commit | de94226e1b302cee2a006f78f0153aa5fa081f47 (patch) | |
| tree | 31859ec7de767dafe5e7474e14f74f473eab6ba8 /animation.lua | |
| parent | 8f9182baff36d33c07c5eb8df795e3cfcd5307a5 (diff) | |
player and animation
Diffstat (limited to 'animation.lua')
| -rw-r--r-- | animation.lua | 68 |
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 |
