Created
December 14, 2012 03:26
-
-
Save mebens/4282502 to your computer and use it in GitHub Desktop.
A Tilemap class. Unsure if the collision code works.
This file contains 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
Sheet = class("Sheet") | |
function Sheet:initialize(img, tileWidth, tileHeight) | |
self.x = 0 | |
self.y = 0 | |
self.image = img | |
self.tw = tileWidth | |
self.th = tileHeight | |
self.quads = {} | |
local i = 1 | |
local iw, ih = img:getWidth(), img:getHeight() | |
for y = 0, ih, tileHeight do | |
for x = 0, iw, tileWidth do | |
self.quads[i] = love.graphics.newQuad(x, y, tileWidth, tileHeight, iw, ih) | |
i = i + 1 | |
end | |
end | |
end |
This file contains 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", Sheet) | |
function Tilemap:initialize(img, columns, rows, tileWidth, tileHeight, solid) | |
Sheet.initialize(self, img, tileWidth, tileHeight) | |
self.cols = columns | |
self.rows = rows | |
self.batch = love.graphics.newSpriteBatch(img) | |
self.solid = solid | |
if solid then self.map = {} end | |
end | |
function Tilemap:draw() | |
love.graphics.draw(self.batch, self.x, self.y) | |
end | |
function Tilemap:set(x, y, index) | |
if index > 0 then self.batch:addq(self.quads[index], x * self.tw, y * self.th) end | |
if self.solid then self.map[y * self.cols + x] = index > 0 end | |
end | |
function Tilemap:load(t) | |
local i = 1 | |
for y = 0, self.rows - 1 do | |
for x = 0, self.cols - 1 do | |
if t[i] > 0 then self:set(x, y, t[i]) end | |
i = i + 1 | |
end | |
end | |
end | |
function Tilemap:collideRect(x, y, width, height) | |
x = math.floor((x - self.x) / self.tw) | |
y = math.floor((y - self.y) / self.th) | |
width = math.floor(width / self.tw) | |
height = math.floor(height / self.th) | |
for ix = x, width - 1 do | |
for iy = y, height - 1 do | |
if self.map[iy * self.cols + ix] then return true end | |
end | |
end | |
return false | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment