Last active
December 10, 2015 05:08
-
-
Save mebens/4385642 to your computer and use it in GitHub Desktop.
Working Tilemap class using a canvas.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Tilemap = class("Tilemap") | |
Tilemap._mt = {} | |
function Tilemap._mt:__index(key) | |
return rawget(self, "_" .. key) or self.class.__instanceDict[key] | |
end | |
Tilemap:enableAccessors() | |
function Tilemap:initialize(img, fw, fh, width, height) | |
self.visible = true | |
self._image = type(img) == "string" and love.graphics.newImage(img) or img | |
self._width = width | |
self._height = height | |
self._columns = math.floor(width / fw) | |
self._rows = math.floor(height / fh) | |
self._tileWidth = fw | |
self._tileHeight = fh | |
self._quads = {} | |
self._canvas = love.graphics.newCanvas(width, height) | |
local imgWidth = self._image:getWidth() | |
local imgHeight = self._image:getHeight() | |
for y = 0, math.floor(imgHeight / fh) - 1 do | |
for x = 0, math.floor(imgWidth / fw) - 1 do | |
self._quads[#self._quads + 1] = love.graphics.newQuad(x * fw, y * fh, fw, fh, imgWidth, imgHeight) | |
end | |
end | |
self:applyAccessors() | |
end | |
function Tilemap:draw(x, y, r, sx, sy, ox, oy, kx, ky) | |
if not self.visible then return end | |
love.graphics.draw(self._canvas, x, y, r, sx, sy, ox, oy, kx, ky) | |
end | |
function Tilemap:set(x, y, index) | |
local mx = x * self._tileWidth | |
local my = y * self._tileHeight | |
love.graphics.setCanvas(self._canvas) | |
love.graphics.setScissor(mx, my, self._tileWidth, self._tileHeight) | |
self._canvas:clear() | |
love.graphics.setScissor() | |
if index > 0 then | |
love.graphics.drawq(self._image, self._quads[index], mx, my) | |
end | |
love.graphics.setCanvas() | |
end | |
function Tilemap:setRect(x, y, width, height, index) | |
local tw = self._tileWidth | |
local th = self._tileHeight | |
love.graphics.setCanvas(self._canvas) | |
love.graphics.setScissor(x * tw, y * th, width * tw, height * th) | |
self._canvas:clear() | |
love.graphics.setScissor() | |
if index > 0 then | |
local quad = self._quads[index] | |
for i = x, x + width - 1 do | |
for j = y, y + height - 1 do | |
if index > 0 then love.graphics.drawq(self._image, quad, i * tw, j * th) end | |
end | |
end | |
end | |
love.graphics.setCanvas() | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment