My favorite way to do tiles is like this:
Code: Select all
tileimages = {
love.graphics.newImage("grass.png"),
love.graphics.newImage("sand.png"),
love.graphics.newImage("water.png"),
}
tilesize = 32
map = {
{1,2,1,1,2,2,2,3},
{1,1,1,2,2,2,3,3},
{1,1,1,2,2,3,3,3},
{1,1,2,2,2,2,3,3},
{1,1,2,2,2,2,3,3},
{1,1,1,1,2,2,2,3},
{1,1,2,1,2,2,3,3},
{1,1,1,1,2,2,3,3},
}
What you're looking at is a table of tables. The table "map" contains rows, which contain the ID number of tiles (instead of an ID number, you could use an image, a table of data, etc.). This is an 8x8 map, but tables in Lua can be any size, so you could make it as big or small as you want.
Why do it like this? Because then you can use one of Lua's most useful features to its full advantage: For pairs in table. For example, to draw all of those tiles, this is all the code we'd need:
Code: Select all
function love.draw()
for x, row in pairs(map) do
for y, tile in pairs (row) do
love.graphics.draw(tileimages[tile], x*tilesize, y*tilesize)
end
end
end
This works: For pairs in table is a kind of loop which operates once on every key/value pair in a given table. As you can see, we do this to the "map" table, and assign the variables "x" and "row" to the key and value it's iterating over. "x" is going to be a number, and "row" is going to be a table. The first pair will be, for example, 1 and {1,2,1,1,2,2,2,3}. So what do we do with this? We iterate over /that/ table, too, assigning numbers to "y" and "tile". The first pair will be 1 and 1.
Then drawing it is pretty simple. We set the position according to "x" and "y", and the image to use a graphic from the "tileimages" table (tileimages[1] is a grass tile, tileimages[2] is a sand tile, etc.).
That should get you started in the right direction. If you need more explanation, feel free to ask.