Skip to content

Instantly share code, notes, and snippets.

@mebens
Created December 14, 2012 03:26
Show Gist options
  • Select an option

  • Save mebens/4282502 to your computer and use it in GitHub Desktop.

Select an option

Save mebens/4282502 to your computer and use it in GitHub Desktop.

Revisions

  1. Michael Ebens created this gist Dec 14, 2012.
    20 changes: 20 additions & 0 deletions Sheet.lua
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    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
    45 changes: 45 additions & 0 deletions Tilemap.lua
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    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