(Swift + Spritekit) - 完全删除节点及其数据

时间:2015-03-23 17:15:43

标签: ios swift sprite-kit skspritenode

我正在为iOS开发一款小游戏。

我的场景中有一个SKSpriteNode - 当我用" removeFromParent"删除它时并触摸它最后的区域,我仍然得到了这个功能。

我的代码如下:

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    /* Called when a touch begins */

    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)

        if tapToPlayNode.containsPoint(location){
            tapToPlayNode.removeFromParent()
            startNewGame()
        }
    }
}

func startNewGame(){
    //Starts a new game with resetted values and characters in position
    println("Ready.. set.. GO!")

    //Shows the ui (value 1)
    toggleUiWithValue(1)
}

换句话说,我得到了#34;准备好......设置...... GO!"即使在删除区域后我也会触摸该区域。

任何线索?

贝斯茨,

1 个答案:

答案 0 :(得分:2)

您的tapToPlayNode仍由自己保留,并从其父级中删除。 您应该将其设为可选var tapToPlayNode:SKSpriteNode?,并在将其从此父级中删除后将其设为nil:

if let playNode = self.tapToPlayNode {
   for touch: AnyObject in touches {
   let location = touch.locationInNode(self)

        if playNode.containsPoint(location) {
            playNode.removeFromParent()
            startNewGame()
            self.tapToPlayNode = nil // il it here!
            break
        }
    }
}

您还可以避免保留tapToPlayNode的引用,并在初始化时为其命名:

node.name = @"tapToPlayNodeName"
// Add node to scene and do not keep a var to hold it!

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */

    // Retrieve the ode here
    let tapToPlayNode = container.childNodeWithName("tapToPlayNodeName")!
    for touch: AnyObject in touches {
       let location = touch.locationInNode(self)

        if tapToPlayNode.containsPoint(location){
            tapToPlayNode.removeFromParent()
            startNewGame()
        }
    }
}