TileMap = {} TileMap.__index = TileMap function TileMap:new(size, tiles, map, blendMode, canvasWidth, canvasHeight) local this = {} this.size = size this.tiles = tiles or {} this.map = map or {} this.blendMode = blendMode this.canvasWidth = canvasWidth or 320 this.canvasHeight = canvasHeight or canvasWidth or 200 this.offsetX = 0 this.offsetY = 0 this.tilesCanvasW = math.floor(this.canvasWidth / this.size) this.tilesCanvasH = math.floor(this.canvasHeight / this.size) this.canvas = love.graphics.newCanvas(this.canvasWidth, this.canvasHeight) return setmetatable(this, TileMap) end function TileMap:random(x, y) local map = {} local tilesCount = #self.tiles -- Заполнение массива for i = 1, y do map[i] = {} for j = 1, x do map[i][j] = math.random(1, tilesCount) end end self.map = map end function TileMap:update() if self.map[1] == nil then return end local mapHeight = #self.map local mapWidth = #self.map[1] local x = self.offsetX local y = self.offsetY local jOffset = math.max(math.floor(x / self.size) + 1, 1) local iOffset = math.max(math.floor(y / self.size) + 1, 1) -- print(x, iOffset) if jOffset > mapWidth or iOffset > mapHeight or -x >= self.canvasWidth or -y >= self.canvasHeight then return end local jUpper = math.min(jOffset + self.tilesCanvasW, mapWidth) local iUpper = math.min(iOffset + self.tilesCanvasH, mapHeight) local prevCanvas = love.graphics.getCanvas() love.graphics.setCanvas(self.canvas) local prevBlendMode = love.graphics.getBlendMode() love.graphics.setBlendMode(self.blendMode) love.graphics.clear(0, 255, 0) -- TODO: debug local spriteY = self.size * (iOffset - 1) - y for i = iOffset, iUpper do local spriteX = self.size * (jOffset - 1) - x for j = jOffset, jUpper do local tileIndex = self.map[i][j] love.graphics.draw(self.tiles[tileIndex], spriteX, spriteY) -- love.graphics.print(tostring(tileIndex), spriteX, spriteY) spriteX = spriteX + self.size end spriteY = spriteY + self.size end love.graphics.setBlendMode(prevBlendMode) love.graphics.setCanvas(prevCanvas) end function TileMap:draw(x, y) love.graphics.draw(self.canvas, x, y) end