1
0
dodge-bolt/src/systems/sprite.lua
2022-08-21 22:56:16 +00:00

104 lines
2.4 KiB
Lua

local data = require("data")
local pprint = require("lib.pprint")
local Vec = require("lib.brinevector")
local Sprite = {}
Sprite.required_groups = {"sprite", "image"}
function Sprite:addToGroup(group, e)
if group == "sprite" then
local sprite = data.sprites[e.sprite.name]
assert(sprite, ("Attempt to draw unknown sprite: %s"):format(e.sprite.name))
for _, slice in ipairs(sprite.slices) do
if slice.user_data and slice.user_data:find("collider") then
self.pool:queue{
pos = e.pos - Vec(sprite.width, sprite.height)/2,
collider = {
slice.x,
slice.y,
slice.x + slice.width,
slice.y + slice.height
}
}
end
end
elseif group == "image" then
assert(e.image:typeOf("Drawable"), ("Expected sprite to be a drawable or aseprite sprite, got: %s"):format(e.image))
end
end
function Sprite:update(dt)
for _, e in ipairs(self.pool.groups.sprite.entities) do
local sprite = data.sprites[e.sprite.name]
if sprite then
local variant = sprite.variants[e.sprite.variant or "default"]
e.sprite.timer = (e.sprite.timer or 0) + dt
if variant then
local frame = variant[e.sprite.frame]
if not frame then
frame = variant[1]
end
if e.sprite.timer > frame.duration then
e.sprite.timer = e.sprite.timer % 0.1
e.sprite.frame = (e.sprite.frame or 1) % #variant + 1
end
end
end
end
end
function Sprite:draw()
love.graphics.setColor(1, 1, 1)
for _, e in ipairs(self.pool.groups.sprite.entities) do
local sprite = data.sprites[e.sprite.name]
assert(sprite, ("Attempt to draw unknown sprite: %s"):format(e.sprite.name))
if not e.hidden then
local variant = sprite.variants[e.sprite.variant or "default"]
local frame_idx = e.sprite.frame or 1
if variant and frame_idx then
local rotation = nil
local frame = variant[frame_idx]
if not frame then
frame = variant[1]
end
local sx = 1
if e.sprite.flip then
sx = -1
end
if e.sprite.wobble then
rotation = math.sin(love.timer.getTime()*10)*0.15
end
love.graphics.draw(
frame.image,
e.pos.x,
e.pos.y,
rotation,
sx, 1,
sprite.width/2, sprite.height/2
)
end
end
end
for _, e in ipairs(self.pool.groups.image.entities) do
if not e.hidden then
local width, height = e.image:getDimensions()
love.graphics.draw(
e.image,
e.pos.x,
e.pos.y,
0,
1, 1,
width/2, height/2
)
end
end
end
return Sprite