Using layers, and ordering within layers based on y position. In some games, you want to have discrete rendering layers for objects. You also want to have objects on layers to be sorted based on y position so that higher objects on the plane are drawn behind objects which are in front of their y position.
Script by @Andreas_Jirenius
Download:
render_order.script (218 Bytes)
render_order.script source
local layer_z = { -0.9, 0.0, 1.0 } -- layer 1, layer 2, layer 3 with default z values
go.property("layer",1) -- exposes this value to be able to be changed in editor, defaults to 1
function update(self, dt)
local pos = go.get_position()
pos.z = layer_z[self.layer]-pos.y*0.0001 -- start with layer z default, modify it based on y position
go.set_position(pos)
end
Add this script as a component to any game object you wish to sort based on layer and y position. You could extend it further for example by adding an additional optional offset property to make certain objects stay on discrete whole number layers but still be above or below everything else on that layer without needing to define more layers.
Remember that your camera z position matters for what is able to be seen by your camera. If you position at z positions behind your camera anything there won’t be visible and so won’t be drawn.
Adding scripts to objects has a runtime cost, and having too many scripts can cause you to hit the default script limit. If you want to sort or manage hundreds of bullets for example it would be better to do that from a single script and not have every bullet object have its own copy of the script.