Reputation: 51
I have a game where a contact with the enemy ends the game but when I use removeFromParent on the enemy node it only removes the most recent one. The enemies are spawned using a switch statement to determine what side they enter from and once a contact happens and the game ends the nodes still present mess up the game by causing more contacts. If the user doesn't press anything and the enemies finish their trajectory during the game over screen then the problem doesn't occur.
Could I kill all the nodes from the screen any way once the game ends? Could I suspend input for like 3 seconds during the end screen to let the actions finish? Do I need to enumerate the enemies as they spawn to kill them off one by one once the game ends?
I've been stuck on this for like 3 days and would love some help. I think I explained it fairly well but if I need to show any code please ask and I will. I'm very new to swift by the way.
Upvotes: 5
Views: 5764
Reputation: 143
In your scene class you can write
// For all children
self.removeAllChildren()
// Removing Specific Children
for child in self.children {
//Determine Details
If child.name == "bob" {
child.removeFromParent
}
}
Upvotes: 9
Reputation: 10664
Enumerating is probably the best way. I would give all your enemies a name(s)
let enemyName = "Enemy" // make it a property to avoid typos
myEnemySprite.name = enemyName
and than if you want to delete a particular set of enemies you can enumerate the scene and remove them
enumerateChildNodesWithName(enemyName) { (node, _) in
node.removeFromParent()
}
Note: If your enemies are children of another node (e.g enemyNode) instead of the scene you will have to enumerate like this
enemyNode.enumerateChildNodesWithName(enemyName) { (node, _) in
node.removeFromParent()
}
Alternatively you could also put all your enemies into an array after you added them to the scene.
Create the array
var enemiesArray = [SKSpriteNode]()
and than for each enemy you add to the scene you add them to the array as well
addChild(yourEnemy1Sprite)
enemiesArray.append(yourEnemy1Sprite)
Now if you want to delete them you can do this
for enemy in enemiesArray {
enemy.removeFromParent()
// clear array as well if needed
}
Hope this helps
Upvotes: 3
Reputation: 533
You can use the SKNode
's method removeAllChildren()
. Call it in the enemies' parent node. If it's the scene, the call should be scene.removeAllChildren()
.
Upvotes: 4