Swift 2.x: 在节点树中搜索多个命中

Swift 2.x: searching the node tree for multiple hits

我想在我的 SKScene class 中搜索以 "spaceship" 开头的子节点。基本上我有几个名为 "spaceship1"、"spaceship2"、"spaceship3" 等的宇宙飞船节点...

但是我的语法不正确。这个:

self.subscript("spaceship[0-9]")

结果:

 Expected ',' separator

还有这个:

self.objectForKeyedSubscript("spaceship[0-9]")

结果:

'objectForKeyedSubscript' is unavailable: use subscripting

这是在 Swift 中使用字符串的非常方便的参考。 http://useyourloaf.com/blog/swift-string-cheat-sheet/

根据该网站

let spaceshipString = "spaceship1"
spaceshipString.hasPrefix("spaceship")    // true
spaceshipString.hasSuffix("1")    // true

考虑到这一点,您可以通过执行以下操作来枚举所有节点以找到带有宇宙飞船的节点。

 func findSpaceShipNodes() {
    self.enumerateChildNodesWithName("//*") {
        node, stop in
            if (( node.name?.hasSuffix("spaceship") ) != nil) {
              // Code for these nodes in here //
            }
    }
}

对于这个问题,有比分配 "spaceship" + counter.

这样的标签更好的方法

宇宙飞船class

是的,出于多种原因,您应该创建一个 Spaceship class,像这样

class Spaceship: SKSpriteNode {

    init() {
        let texture = SKTexture(imageNamed: "spaceship")
        super.init(texture: texture, color: .clearColor(), size: texture.size())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

取回所有飞船

class GameScene:SKScene {
    var spaceships: [Spaceship] {
        return self.children.flatMap { [=11=] as? Spaceship }
    }
}

为什么自定义 class 优于 "numbered tags"

有几个原因

  1. 你不会疯狂地为每个应该像宇宙飞船一样工作的新精灵分配一个新的带有计数器的标签值
  2. 您只需向 Spaceship 添加方法即可向 Spaceship 实体添加行为 class。
  3. 如果您错误地将另一个节点用作飞船,编译器将阻止您
  4. 你的代码更干净