【问题标题】:How to get all child nodes with name in Swift with Scene Kit如何使用 Scene Kit 在 Swift 中获取所有具有名称的子节点
【发布时间】:2018-01-09 19:10:14
【问题描述】:

我正在尝试开发一个基本游戏,并且我有一个场景,其中添加了几个子节点到根节点。每个节点都有两个名称之一,friendenemy

如果用户触摸其中一个enemy 节点,我想删除所有 个名为enemy 的子节点。

我已经尝试了几件事,但似乎没有任何效果。

在我的touchesBegan 函数中:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
   let touch = touches.first!
   let location = touch.location(in: gameView)
   let hitList = gameView.hitTest(location, options: nil)

   if let hitObject = hitList.first {
      let node = hitObject.node

      //This doesn't work
      gameScene.rootNode.childNodes(passingTest: { (node, UnsafeMutablePointer<ObjCBool>) -> Bool in 
      node.removeFromParentNode()
   } 
}

我也尝试过使用gameScene.rootNode.enumerateChildNodes(withName:),但我也无法使用。

可以工作的是,如果我在那里做这样的事情:

if node.name == "enemy" {
    node.removeFromParentNode()
}

但是,这只会删除被击中的单个节点,而不是全部。如何使用 Scene Kit 在 Swift 中获取具有特定名称的所有子节点?

【问题讨论】:

  • enumerateChildNodes(withName: "enemy", using: { node, _ in })
  • @ElTomato 这给了我一个错误Extra argument 'using' in call
  • enumerateChildNodes(withName:) 应该可以工作,这里有一个例子:stackoverflow.com/a/26748966/1187415
  • @MartinR 我相信 OP 正在使用 SceneKit(SCNNode 实例)而不是 SpriteKit;两者之间通常存在重叠,但似乎为SKNode 提供的enumerateChildNodes(withName:using:) 方法对SCNNode 不存在。 childNodes(passingTest:) 可能用于后者,或者只是对 childNodes 属性的 filter 调用;虽然我不确定这些对于多子层次结构是否等效(节点层次结构深度> 1)。
  • @dfri:这就解释了,谢谢。

标签: swift scenekit


【解决方案1】:

过滤掉名称匹配的节点,并从父节点中移除:

gameScene.rootNode.childNodes.filter({ $0.name == "Enemy" }).forEach({ $0.removeFromParentNode() })

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-10-08
  • 1970-01-01
  • 2019-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-08
相关资源
最近更新 更多