【问题标题】:(Swift + Spritekit) - remove node and its data entirely(Swift + Spritekit) - 完全删除节点及其数据
【发布时间】:2015-03-23 17:15:43
【问题描述】:

我正在为 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)
}

换句话说,我得到“Ready.. set.. GO!”即使在删除区域后,当我触摸该区域时也会输出。

有什么线索吗?

最佳,

【问题讨论】:

    标签: ios swift sprite-kit skspritenode


    【解决方案1】:

    您的 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?”我似乎无法对节点进行纹理处理?
    • @bsarr007 重新启动新游戏后是否必须将 SKSpriteNode 设为 nil,或者在开始新游戏之前将其从父级中删除后它是否仍然有效?目前我需要擦除一个可选的 SKSpriteNodes 列表,但在从父级删除后将它们设置为 nil 似乎不起作用。谢谢。
    • @J.Treutlein,我不知道你的问题,但在我给出的第二个例子中,你不必什么都没有,SpriteKitNode "tapToPlayNodeName" 只是被名称引用,那里没有保存它的变量,在将它从它的父级中删除后,它就不再被引用了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    相关资源
    最近更新 更多