SpriteKit:找到某些 class 的 SKNode 的所有后代?

SpriteKit: find all descendants of SKNode of certain class?

展示了如何找到属于某个 class 的 SKNode 的所有子节点,但是如果我们想要属于某个 [=20] 的所有后代(例如,孙子)怎么办=]?

在 SpriteKit 中是否有一种本地方法可以做到这一点,或者是根据上述问题创建递归形式的解决方案的唯一选择?

SKNode 文档强调了一个搜索功能,可以让您找到具有特定名称的后代,但是有没有办法通过 class 而不是名称来过滤后代?如果可以避免,我们不想为节点分配名称。

我们正在使用 Swift 3.

我们所做的是将一个块传递给按名称查找节点的 SKNode 函数,并使用 * 作为搜索词以避免为所需节点分配名称。

    var descendants = [CustomClass]()
    nodeToSearch.enumerateChildNodes(withName: ".//*") { node, stop in
        if node is CustomClass {
            descendants.append(node as! CustomClass)
        }
    }

只需将此扩展程序添加到您的项目中

import SpriteKit

extension SKNode {
    func allDescendants<Element: SKNode>(byType type: Element.Type) -> [Element] {
        let currentLevel:[Element] = children.flatMap { [=10=] as? Element }
        let moreLevels:[Element] = children.reduce([Element]()) { [=10=] + .allDescendants(byType: type) }
        return currentLevel + moreLevels
    }
}

现在您可以获取具有特定类型(例如 SKSpriteNode)的 SKNode 的所有后代

let descendants = node.allDescendants(byType: SKSpriteNode.self)

例子

class Enemy: SKSpriteNode { }

let root = SKNode()
let a = Enemy()
let b = SKNode()
let c = SKNode()
let d = Enemy()

root.addChild(a)
root.addChild(b)
a.addChild(c)
a.addChild(d)

let enemies: [Enemy] = root.allDescendants(byType: Enemy.self)

print(enemies.count) // 2