从数组 spritekit swift 中删除节点

Posted

技术标签:

【中文标题】从数组 spritekit swift 中删除节点【英文标题】:remove node from array spritekit swift 【发布时间】:2016-09-20 09:18:32 【问题描述】:

我正在开发一款适用于 ios 的小游戏(spritekit/swift)。

我的场景中有一个 SKSpriteNode 数组,定义如下:

var spritesTree = [SKSpriteNode]()

然后我用一个函数填充数组并将它们添加到场景中,如下所示:

spritesTree = spritesCollectionTree(count: numTrees)
    for sprite in spritesTree 
        addChild(sprite)
    

之后,根据具体情况,进程会在数组中添加更多树。如果我知道索引,我知道如何从场景和数组中删除元素

            spritesTree[i].removeFromParent()
            spritesTree.removeAtIndex(i)

但我的问题是当我不知道索引时删除此数组中的特定节点。例如,当其中一个精灵被触摸时

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) 
    /* Called when a touch begins */

    for touch in (touches as! Set<UITouch>) 

        let location = touch.locationInNode(self)
        let positionInScene = touch.locationInNode(self)
        let touchedNode = self.nodeAtPoint(positionInScene)

在这种情况下,¿如果我不知道索引,我如何从 SKSpriteNode 的数组 spritesTree 中删除 touchNode?我之前阅读了一些关于 indexOf 的内容来查找索引,但它不适用于我的 SKSpriteNode 数组。你能帮帮我吗?

最佳,

【问题讨论】:

【参考方案1】:

您可以为每个 SKSpriteNode 创建一个名称:

spritesTree[index].name = String(index) 

当您检查节点后,您将名称转换为 Int

    let location = touch.locationInNode(self)
    let positionInScene = touch.locationInNode(self)
    let touchedNode = self.nodeAtPoint(positionInScene)
    var index = Int(touchedNode.name)
    touchedNode.removeFromParent()
    spritesTree.removeAtIndex(index)

【讨论】:

感谢您的回答,但它并没有完全解决我的问题。想象一下,我有以下与位置匹配的列表节点名称 ["0","1","2","3","4"]。当我删除名称为 '2' 的第一个项目时,一切正常,但如果我尝试使用名称为 '4' 的 removeAtIndex 则失败,因为这些项目已按位置 0->"0", 1 重新组织->"1", 2->"3", 3->"4" 现在数组中没有“4”位置。你知道是否有任何函数可以从名称中返回项目位置吗? 在循环中删除后全部重命名。或者你可以尝试像这样在数组中找到节点:for index in 0...spritesTree.count if touchNode == spritesTree[index] spritesTree.removeAtIndex(index)

以上是关于从数组 spritekit swift 中删除节点的主要内容,如果未能解决你的问题,请参考以下文章

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

在 Swift SpriteKit 中禁用节点和 FPS 标签

touchesBegan Swift 2 自定义 SpriteKit 节点

在 spritekit swift 中触摸节点时没有播放声音

基本的 swift/spritekit 游戏 - 麻烦重绘

Spritekit 节点未从内存中删除