[Solution] How to bring sprite to front

I came upon a neat lil trick after messing around with z-order and such for bringing a sprite to front.

auto spriteParent = sprite->getParent();
spriteParent->reorderChild(sprite, (int)spriteParent->getChildrenCount() - 1);

boom! done.

enjoy,

Haven’t used reorderChild before. Does this work if another child has been set to a higher Z-order previously or is this separate from Z-order?

e.g. If Parent has 2 children and I set the Z-order of Child1 to 10, if I use your code on Child2 will it bring Child2 to the front or just set its Z-order to 1?

@grimfate I wasn’t having much luck with just messing with Z-orders, local or global. I’m not sure what it’ll do in the case where you have the explicit assignments. But for reorderChild(), orderOfArrival is used as tie breaker between Z-orders.

bool nodeComparisonLess(Node* n1, Node* n2)
{
    return( n1->getLocalZOrder() < n2->getLocalZOrder() ||
           ( n1->getLocalZOrder() == n2->getLocalZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() )
           );
}

Interesting.

Also, I was just looking at the code for reorderChild in v3.8.1 and found a comment related to the order of arrival thing that I found kinda funny xD

// FIXME:: Yes, nodes might have a sort problem once every 15 days if the game runs at 60 FPS and each frame sprites are reordered.

(Note: That will likely be once every 15 days if it is running non-stop the entire time.)

We’ve used remove then add which behaves correctly for most nodes, but this would be smarter and more correct.

Might be nice if bringToFront and sendToBack methods existed on Node? Granted the code here is fairly concise and others can create their own wrapper methods with those names if they want.

Also, in the default case it’s simpler if you don’t set any explicit Z order on the parent’s children.

sprite->getParent()->reorderChild(sprite, 0);

I tried this in a for loop, for bringing 4 sprites to front amongst 16 sprites in a layer, but it didn’t work. Any idea how to do it ?