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?
Filter out the nodes with matching name and remove them from the parent node:
gameScene.rootNode.childNodes.filter({ $0.name == "Enemy" }).forEach({ $0.removeFromParentNode() })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With