Page 1 of 1

help with sorting

Posted: Tue Apr 01, 2014 9:06 pm
by sanjiv
I'm working on a pseudo 3d system, where objects have x,y, and z coordinates. When I draw them on screen, I want to draw stuff with lower x, y, and z values first, and stuff with higher x, y, and z values last. How can I sort objects based on their values?

Or rather, is there a pre-existing version of table.sort I can use, or do I have to make a custom sorting function?

exampleTable={
{"item1", x=0,y=1,z=1},
{"item2", x=5,y=1,z=1},
{"item3", x=0,y=7,z=1}
}

and I'd draw items using something like

for i=1,#exampleTable do
draw(exampleTable)
end

Re: help with sorting

Posted: Tue Apr 01, 2014 9:39 pm
by Jasoco
table.sort is your answer.

Here's how I use it in my 3D system. Make sure you give each "drawable object" a "depth" value. Then use table.sort to sort by distance from the camera like so:

Code: Select all

table.sort( drawableObjects,
	function(a, b)
		return a.depth > b.depth
	end
)
I give mine an extra layer of sortability by adding a "layer" parameter to every object with a number from -infinity to +infinity which lets it draw specific layers before others. (For instance, background stuff like environment draws first, maybe a special layer for water effects, the normal 3D world layer and if needed a 3D rendered overlay or something.)

It also depends on your definition of 3D. Is it 3D like Wolfenstein or 3D like Star Fox?
Screen Shot 2014-04-01 at 5.37.09 PM.png
Screen Shot 2014-04-01 at 5.37.09 PM.png (102.82 KiB) Viewed 1113 times