summaryrefslogtreecommitdiff
path: root/Sprite.lua
blob: dac5ce8d287fe826e992c52a9dc25197d7c11126 (plain)
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
local component = require 'component'
local Transform = require 'Transform'
local Drawable = require 'Drawable'

local Sprite = component({Drawable}, {Transform})

local function load_image(path)
	return love.graphics.newImage(path, {dpiscale = 2})
end

local loaded = setmetatable({}, {__mode = 'v'})
local function get_states(name)
	if loaded[name] then return loaded[name] end
	loaded[name] = {}

	local path = "sprite/"..name
	if love.filesystem.getInfo(path..".png", 'file') then
		loaded[name][name] = load_image(path..".png")
	elseif love.filesystem.getInfo(path, 'directory') then
		local files = love.filesystem.getDirectoryItems(path)
		for _, file in ipairs(files) do
			local state = file:match '^(.*)%.png$'
			if state then
				loaded[name][state] = load_image(path.."/"..file)
			end
		end
	end
	return loaded[name]
end

function Sprite:init(inst)
	assert(inst.name)
	inst.state = inst.state or inst.name
	inst.states = get_states(inst.name)
end

function Sprite:draw()
	self.obj[Transform]:use()
	local i = self.i.states[self.i.state]
	local w, h = i:getDimensions()
	love.graphics.draw(i, 0, 0, 0, 1, 1, w / 2, h / 2)
end

function Sprite:bee()
	print "apioform"
end

return Sprite