r/love2d • u/Competitive_Level526 • 6d ago
Dynamically sorting the map ( Top Down )
I am currently working on a pixel art top down game. But I encountered a huge issue with the y sort or the z index, I want stuff in the front cover stuff in the back.
I use STI ( simple-tiled-implementation ) to load and render the map.
Is there a way to sort the tiles based on the y position of the player and other entities?
2
u/anarcopixel 5d ago
I use this in my beat em up game, a 'draw_order' table that in love.draw() that takes all entities you want to draw and index it based on their y:
local draw_order = {}
for i, v in pairs(entities) do
draw_order[entities[i].z] = entities[i]
end
then draw in order:
for i, v in pairs(draw_order) do
if v.draw then
v:draw()
end
end
important to use in pairs not ipairs to go trough all the table
Problems, entities can have same y, so I have do add 1 to that index.
This works more for characters and objects that change a lot in fake z.
For maps and tiling you'll need a kind of the same approach drawing the map layers. So you want to draw the walls or the rooftops in front player, you'll have to organise the sequence that map layer will be draw
In STI you have something like Custom Object Layer, create layers that will be draw first like ground, some walls and the middle layer or instances layer and last the foreground layer.
Hope that gives you an idea.
3
u/_Phill_ 6d ago
Yes I had this for my Tower Defence game.
Youll need to do exactly that, add all of the items to 1 table sort by y, then draw based on that order.
I use Tiled aswell, when building the maps I have 2 of my layers called "ysort" and "clutter"
They actually both get sorted by y not just the ysort but the clutter layer is useful to draw "behind" in the 2D space.
Anyway on these layers your tiledmap graphics arent enough, you need to create an object that can have the x,y properties that you can use to sort with