Scroll all the SKNode kids?

I have a SKNode with a number of child SKSpriteNodes. A simplified example:

var parentNode = SKNode()
var childNode1 = SKSpriteNode()
var childNode2 = SKSpriteNode()

self.addChild(parentNode)
parentNode.addChild(childNode1)
parentNode.addChild(childNode2)

I want to run an action colorizeWithColorfor all these children. When I run the action on parentNode, there is no effect.

I cannot use enumerateChildNodesWithNamefor a parent because many of his descendants have names that I use.

Is there a way to scroll through all the children parentNodein order to perform one action for all of them?

+4
source share
3 answers

You can simply list parentNode.children:

for child in parentNode.children as! [SKNode] {
    // ...
}

If necessary, check each child, if he is actually SKSpriteNode:

for child in parentNode.children {
    if let spriteNode = child as? SKSpriteNode {
        // ...
    }
}

Swift 2 (Xcode 7), for case:

for case let child as SKSpriteNode in parentNode.children {
    // ...
}
+17

, children, colorizeWithColor .

let children = parentNode.children
for child in children {
    // Do something.
}
+1

2017 .

for case let child as SKSpriteNode in parentNode.children {
    // ...
}

.

: .

.

, "" " ", , , . , .

, ...

    // try Apple native .children call...

    for case let s as SomeSpriteClass in children { k += 1 }
    let t1 = a.microseconds()

    // simply use your own list...

    let b = Date()
    for s in spaceships { k += 1 }
    let t2 = b.microseconds()

    print("\(t1) \(t2)")

it's 3 or 4 times faster if you just iterate over your own list.

Typical iPad output ...

939 43
140 33
127 33
117 37
109 30
126 33
127 33
109 29
96 30
96 29
99 30
97 30
97 30

(In particular, as you would expect, the built-in enumeration takes forever the "first" time.)

Given performance, in practice, you need to keep your own list of sprites and do it.

+1
source

Source: https://habr.com/ru/post/1570724/


All Articles