-- Tilemap entity, it dynamically rebuilds its draw cache thingy -- You just need to worry not and use the tile getting/setting functions TILESIZE = 16 function new_tilemap(width, height) local map = new_entity() add_comp(map, "Tilemap", width, height) return map end local function ID(map, x, y) return x + y * map.width + 1 end -- local function POS(map, id) -- id = id - 1 -- return id % map.width, math.floor(id / map.width) -- end register_comp("Tilemap", function(tilemap, width, height) tilemap.tiledata = {} for i=1, width*height do tilemap.tiledata[i] = 0 end tilemap.width = width tilemap.height = height tilemap.cache = {} tilemap.cachesize = 0 tilemap.needs_rebuild = false end) function rebuild_tilemap(map) map.cache = {} for x = 0, map.width - 1 do for y = 0, map.height - 1 do local tile = get_tile(map, x, y) if tile ~= 0 then map.cachesize = map.cachesize + 1 map.cache[map.cachesize] = { x = x * TILESIZE, y = y * TILESIZE, } end end end end function tilemap_draw_sys(tilemap) if tilemap.needs_rebuild then rebuild_tilemap(tilemap) tilemap.needs_rebuild = false end for i=1, tilemap.cachesize do local tile = tilemap.cache[i] lg.circle("fill", tile.x, tile.y, 4) end end function get_tile(map, x, y) return map.tiledata[ID(map, x, y)] end function queue_tilemap_rebuild(tilemap) tilemap.needs_rebuild = true end function set_tile(map, x, y, tileid) map.tiledata[ID(map, x, y)] = tileid map.needs_rebuild = true end function remove_tile(map, x, y) map.tiledata[ID(map, x, y)] = 0 map.needs_rebuild = true end