【问题标题】:SpriteKit: find all descendants of SKNode of certain class?SpriteKit:查找某个类的 SKNode 的所有后代?
【发布时间】:2017-05-31 01:24:35
【问题描述】:

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

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

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

我们正在使用 Swift 3。

【问题讨论】:

  • 将该问题的答案转换为 SKNode 上的扩展,然后在其中添加递归调用。
  • @davecom 是的,只是想知道是否有更优雅或更原生的方式来做到这一点,谢谢。

标签: ios swift sprite-kit sknode


【解决方案1】:

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

import SpriteKit

extension SKNode {
    func allDescendants<Element: SKNode>(byType type: Element.Type) -> [Element] {
        let currentLevel:[Element] = children.flatMap { $0 as? Element }
        let moreLevels:[Element] = children.reduce([Element]()) { $0 + $1.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

【讨论】:

  • 这很可爱,应该是公认的答案:)
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-24
    • 2023-03-22
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    • 1970-01-01
    相关资源
    最近更新 更多