1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
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
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, math.floor(x), math.floor(y), 0, sx, sy, ox, oy)
end
return Animation
|