Quick Links: Download Gideros Studio | Gideros Documentation | Gideros Development Center | Gideros community chat
Compare sprites depth (z-index) - Gideros Forum

Compare sprites depth (z-index)

RickyngkRickyngk Member
edited March 2013 in General questions
I try to compare sprites depth (z-index) by using the following code
function Sprite:CompareDepthTo(cmp)
	if cmp == self then return 0 end
 
	p1 = self:getParent()
	p2 = cmp:getParent()
	if p1 == cmp then --cmp is parent of self
		return 1 
 
	elseif self == p2 then --self is parent of cmp
		return -1 
 
	elseif p1 == p2 and p1 ~= nil then -- the same root
		return p1:getChildIndex(self) > p1:getChildIndex(cmp) and 1 or -1
 
	else --complicated relationship
		local p1 = self
		local p2 = cmp
		local pp1 = {}
		local pp2 = {}
		while p1 ~= nil do
			pp1[#pp1 + 1] = p1
			p1 = p1:getParent()
		end
		while p2 ~= nil do
			pp2[#pp2 + 1] = p2
			p2 = p2:getParent()
		end
 
		local m = math.min(#pp2, #pp1)
		local index = 0
 
		for i = 0, m - 1 do
			index = i
			if pp2[#pp2 - i] ~= pp1[#pp1 - i] then break end
		end
 
		if index == 0 then -- not the same root
			return nil
		elseif index == m - 1 then -- one of them are parent/root of other, for ex: [19 17 15 4 2 1] <-> [15 4 2 1]
			return #pp1 > #pp2 and 1 or -1
		else
			local common_p = pp1[#pp1 - index + 1]
			local child1 = pp1[#pp1 - index]
			local child2 = pp2[#pp2 - index]
			return common_p:getChildIndex(child1) > common_p:getChildIndex(child2) and 1 or -1
		end
	end
end
return :
+ (1): means self stays above
+ (-1): self stays below
+ (0): compare self itself
+ (nil): unknown, there's no relationship

I'm afraid of its performance, any better solution? :D

P/S: I also attach sample code.

Likes: anneMurielle

+1 -1 (+1 / -0 ) Share on Facebook

Comments

Sign In or Register to comment.