sorting


HOWTO SPRITE SORTING IN 2D SCREEN SPACE

Hi. It is not an easy task to sort sprites so the game does not look like you draw first bottom sprites, then from right to left, then top sprites and override the screen with nonsense looking pixel mess output.

In lua there are tables in which you put objects and these objects contain x,y position values.

-- define objects array with 4 object tables, each on different position
local objects = {}
objects[1] = {x = 12, y = 25}
objects[2] = {x = 5, y = 30}
objects[3] = {x = 1, y = 10}
objects[4] = {x = 30, y = -10}

It is good to sort these not every draw call. Maybe not every update call but at least call it each 10 frames.

Then, in order to work correctly you generate a position hash to the sprites visible like this:

-- the y,x are formated as 5 digits starting with zeroes for example 00005_00003
for i,object in ipairs(objects) do
 object.hash_position = string.format("%05d_%05d",math.floor(object.y+object.dy),math.floor(object.x+object.dx))
end

The main trick to this is to not sort directly by x,y position because this will get you into mess fast. But use the string hash instead which looks quite dirty. Perhaps think, that this is a big number you can sort and it would be even faster!

-- a,b are objects compared by hash_position, where objects that are higher on screen and left are draw first than objects going down or right.
function func_sort(a,b)
 return a.hash_position < b.hash_position
end

After doing this to each object you have in the array you call table.sort(objects,func_sort) where objects is the table in which you stored all the game objects on game screen.

print("sorted result check")
table.sort(objects,func_sort)
for i,object in ipairs(objects) do
 print("y",object.y,"x",object.x)
end

Look at the result and see that the Y is sorted first from smaller numbers to higher numbers. Then the X is sorted from left to right on screen.

Comments

Log in with itch.io to leave a comment.

Also if you want to speed up the sort you can skip the string conversion of y,x as hash and use instead a number representation. When the coordinate is multiplied by a equation hash_position = y*100000 + x you get a big number which is easier to calculate, takes less space in bytes and the table sort will be faster.