Contents

Tile Access

Most maps will be made up of tiles; that's most of what Tiled is for, after all. When you need access to a tile in your game, you can use one of several methods. All of these methods are methods of a tile layer object, which is accessed through the map.layer table.



layer.tile(x, y)

This is, perhaps, the simplest method to get a tile from the layer. It will return the tile at tile position (x, y). If the tile is outside the screen border and is not locked from culling, this will be nil.

Though this is the easiest method, if you need access to a tile multiple times in a loop or in a function called often, you should localize the tile when you access it. This is a function, and as such has a bit of overhead every time it's called.

Good:
local tile = map.layer[x].tile(x, y)
tile.someCustomProperty = true
tile.somethingElse = 48.6
tile.xyz = 123
Bad:
map.layer[x].tile(x, y).someCustomProperty = true
map.layer[x].tile(x, y).somethingElse = 48.6
map.layer[x].tile(x, y).xyz = 123


layer.tiles[x][y]

Dusk also allows you to access the tile layer's tile grid directly through the tiles table. The tiles table is a matrix of tiles. Really, all the layer.tile(x, y) function does is provide a thin wrapper around this table with error checking.

If the column (X-position) of the tile doesn't exist, you'll get an error, so unless you know the tile exists, you should wrap your access in an if check. This is what the layer.tile(x, y) function does for you.

if map.layer[x].tiles[x] and map.layer[x].tiles[x][y] then
	local tile = map.layer[x].tiles[x][y]
end

This approach is faster than the layer.tile(x, y) function, but the tile should still be localized if you use it often.



layer.tileByPixels(x, y)

This method allows you to grab a tile at a pixel location. Internally, it first converts the location to tile coordinates, then retrieves the tile at that position. Thus, of the methods of getting tiles, this is the slowest. That doesn't mean "don't use it"; it'll actually take the same amount of time as converting and getting the tile. Just don't abuse it, and use it to get tiles to iterate by offsetting pixels or something equally crazy. Instead, this function is useful for getting tiles from a touch event or similar.

local tile = map.layer[x].tileByPixels(pixelX, pixelY)


Iterators

Tile layers also provide a few iterators to get chunks of tiles with. You can read the docs for them here.