Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpriteKit: how to iterate through ancestors of a node?

We want to iterate through the ancestors of a node until we find a parent with a specific class.

SpriteKit lets you iterate through children with the children property, but the parent property only holds the immediate parent -- not an array of parents. How do we iterate through all the ancestors of a node?

like image 661
Crashalot Avatar asked Jan 30 '26 11:01

Crashalot


1 Answers

I'm not aware of a function that lets you go up the hierarchy, similar like the enumerateChildNodes function allows you to go down the hierarchy. Maybe this recursive function may help. Below I've set recursion to end when there is no parent, or when the parent is an SKScene class. You may need to adjust it so that recursion ends when your particular class is found.

func parentNodesOf(_ node: SKNode) -> [SKNode]
{
    if let parentNode = node.parent
    {
        if parentNode is SKScene
        {
            return []
        }
        else
        {
            return [parentNode] + parentNodesOf(parentNode)
        }
    }
    else
    {
        return []
    }
}

Hope this helps!

like image 62
JohnV Avatar answered Feb 02 '26 01:02

JohnV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!