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

3

我正在为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)
}
换句话说,即使我删除了该区域,当我触摸该区域时,仍会输出“准备好了……开始!”。 有什么线索吗?祝好。
1个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
3

你的tapToPlayNode仍被self引用,且已从其父节点中移除。 你应该将其声明为可选类型: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()
        }
    }
}

非常感谢您的迅速回答,Bsarr!不过有一个小问题:当我使用“var tapToPlayNode:SKSpriteNode?”时,好像无法给节点添加纹理? - theloneswiftman
@bsarr007 在重新开始新游戏之前,您是否需要将SKSpriteNode设置为nil,或者在从父节点中删除后仍然有效?目前,我需要清除一系列可选的SKSpriteNodes,但是在它们从父节点中移除后将它们设置为nil似乎并没有起作用。谢谢。 - J.Treutlein
@J.Treutlein,我不确定你的问题是什么,但在我给出的第二个示例中,你不必将任何东西设置为nil。SpriteKitNode“tapToPlayNodeName”只是按名称引用,没有变量来保存它,在将其从其父节点中删除后,它就不再被引用了。 - bsarr007

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,