Sorting GUI nodes based on y position (SOLVED)

What’s wrong with this? It seems to mostly work but nodes will randomly flicker like they are not being moved properly.

game.zip (3.1 KB)

local nodes = {}

local function sort_nodes(self)
	table.sort(nodes,
		function(a, b)
			local a_y = gui.get_position(a[self.template_node_root]).y
			local b_y = gui.get_position(b[self.template_node_root]).y
			return a_y > b_y
		end
	)
	local i = 1
	for k,v in ipairs(nodes) do
		if i ~= #nodes then
			gui.move_below(nodes[k][self.template_node_root], nodes[k+1][self.template_node_root])
		end
		i = i + 1
	end
end

function init(self)
	msg.post("@render:", "clear_color", { color = vmath.vector4(0.3, 0.3, 0.3, 1) } )

	local template_node = gui.get_node("template/root")
	self.template_node_root = hash("template/root")
		
	for i=1, 5 do
		local node = gui.clone_tree(template_node)
		local x = math.random(1,250)
		local y = math.random(1,100)
		local position = vmath.vector3(x,y,0)
		gui.set_position(node[self.template_node_root], position)
		gui.set_color(node[hash("template/box")], vmath.vector3(math.random(100)/100, math.random(100)/100, math.random(100)/100))
		position.y = -100
		gui.animate(node[self.template_node_root], "position", position, gui.EASING_LINEAR, math.random(50)/10, 0, nil, gui.PLAYBACK_LOOP_PINGPONG)
		
		table.insert(nodes, node)
	end
	gui.set_enabled(template_node, false)
end

function update(self, dt)
	sort_nodes(self)
end

Update to sample

game.zip (3.5 KB)

It looks like on some frames even though the sorting of the table is right and goes in order sometimes nodes will have an incorrect index value according to gui.get_index().

s

game.zip (3.5 KB)

It was my fault! Here’s a working sample for GUI sorting based on relative y position.

6 Likes