问题
Im trying to remove SKSpriteNodes from the parent, "self". I create the nodes via a for loop inside a function I call every time I need to update the number of nodes. This nodes represent the number of lives a player has inside the game.
func starsSpwan() {
self.starNode.removeFromParent()
var spaceInX:CGFloat = 0
for var i = 0; i<gameLife; i=i+1 {
starsTexture = SKTexture(imageNamed: "star")
starsTexture.filteringMode = SKTextureFilteringMode.Nearest
starNode = SKSpriteNode(texture: starsTexture)
starNode.zPosition = 30
starNode.size = CGSize(width: 30, height: 30)
starNode.position = CGPoint(x: CGRectGetMinX(self.frame) + 30 + spaceInX, y: CGRectGetMinY(self.frame) + 30)
self.addChild(starNode)
println(starNode)
spaceInX = spaceInX + 40
}
}
Basically the variable gameLife decides how many stars to add. I add the self.starNode.removeFromParent() at the beginning because if the player looses a life I want to delete all 3 stars first and then add again only 2 stars and so on.
My problem is that currently this works only the first time the user looses a life. the nodes get deleted and 2 stars are added again. But if the player looses again another life the nodes don't get deleted and an extra node is added. Still this in unnoticeable because the node is added on top of an existing node.
New code still not working correctly
func starsSpwan() {
self.nodeStar.removeFromParent()
var spaceInX:CGFloat = 0
for var i = 0; i<gameLife; i=i+1 {
starsTexture = SKTexture(imageNamed: "star")
starsTexture.filteringMode = SKTextureFilteringMode.Nearest
starNode = SKSpriteNode(texture: starsTexture)
starNode.zPosition = 30
starNode.size = CGSize(width: 20, height: 20)
starNode.position = CGPoint(x: CGRectGetMinX(self.frame) + 30 + spaceInX, y: CGRectGetMinY(self.frame) + 30)
starNode.name = "stars"
self.addChild(starNode)
println(starNode)
spaceInX = spaceInX + 40
nodeStar = self.childNodeWithName("stars")!
}
}
回答1:
Try the following...
func starsSpawn() {
// Remove all sprites named "stars"
self.enumerateChildNodesWithName("stars") {
node, stop in
node.removeFromParent();
}
var spaceInX:CGFloat = 0
for var i = 0; i<gameLife; i=i+1 {
starsTexture = SKTexture(imageNamed: "star")
starsTexture.filteringMode = SKTextureFilteringMode.Nearest
starNode = SKSpriteNode(texture: starsTexture)
starNode.zPosition = 30
starNode.size = CGSize(width: 20, height: 20)
starNode.position = CGPoint(x: CGRectGetMinX(self.frame) + 30 + spaceInX, y: CGRectGetMinY(self.frame) + 30)
starNode.name = "stars"
self.addChild(starNode)
println(starNode)
spaceInX = spaceInX + 40
}
}
来源:https://stackoverflow.com/questions/26709364/removing-skspitenode-from-parent