Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all child nodes with name in Swift with Scene Kit

Tags:

swift

scenekit

I am trying to develop a basic game and I have a scene with several child nodes added to the root node. Each node has one of two names, either friend or enemy.

If a user touches one of the enemy nodes I want to remove all child nodes that are named enemy.

I have tried several things, but can't seem to get anything working.

In my touchesBegan function:

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()
   } 
}

I have also tried to use gameScene.rootNode.enumerateChildNodes(withName:) but I can't get that working either.

What I can get working is if I do something like this in there instead:

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

However this will only remove the single node that was hit, not all of them. How can I get all of the child nodes with a certain name in Swift with Scene Kit?

like image 745
maxshuty Avatar asked Dec 31 '17 01:12

maxshuty


1 Answers

Filter out the nodes with matching name and remove them from the parent node:

gameScene.rootNode.childNodes.filter({ $0.name == "Enemy" }).forEach({ $0.removeFromParentNode() })
like image 115
Oskar Avatar answered Jan 03 '23 13:01

Oskar