从父级删除SKSpiteNode

时间:2014-11-03 07:07:08

标签: swift sprite-kit

我试图从父母“self”中删除SKSpriteNodes。 我在每次需要更新节点数时调用的函数内通过for循环创建节点。此节点表示玩家在游戏中的生命数。

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
    }

}

基本上变量gameLife决定要添加多少个星星。我添加了self.starNode.removeFromParent()  在开始时因为如果玩家失去生命我想先删除所有3颗星然后再添加2颗星等等。

我的问题是,目前这只是用户第一次失去生命。节点被删除,并再次添加2颗星。但是如果玩家再次失去另一个生命,则节点不会被删除,并且会添加额外的节点。这仍然是不明显的,因为节点被添加到现有节点之上。

新代码仍无法正常使用

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 个答案:

答案 0 :(得分:1)

尝试以下方法......

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