2016-09-20 95 views
1

我正在为iOS(spritekit/swift)开发一个小游戏。从阵列中删除节点spritekit swift

我一直的阵列SKSpriteNode在我的场景定义是这样的:

var spritesTree = [SKSpriteNode]() 

然后我填的是阵列的功能,并将它们添加到场景是这样的:

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

之后,根据情况,该过程会在阵列中添加更多树。我知道如何,如果我知道了指数

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

但我的问题是要删除especific节点本阵时,我不知道索引中删除从场景和数组元素。对于为例,当精灵的一个被感动

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) 

在这种情况下,¿如何从我的阵列spritesTree SKSpriteNode删除touchedNode如果我不知道该指数?我读了一些关于indexOf以前查找索引但它不适用于我的SKSpriteNode数组。请问你能帮帮我吗?

最好成绩,

回答

0

可以为每个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

感谢您的回答,但没完全解决我的问题。想象一下,我有以下与位置匹配的列表节点名称[“0”,“1”,“2”,“3”,“4”]。当我删除名为'2'的第一个项目时,一切都很好,但是如果我尝试使用名称'4'尝试_removeAtIndex_,它将失败,因为项目已被重新组织为位置0 - >“0”,1 - >“1”,2 - >“3”,3 - >“4”,现在阵列中没有“4”位置。你知道是否有任何函数返回名称中的项目位置? – Xavi

+0

在循环中删除后重命名全部。或者你可以尝试找到这样的节点到数组中:for index in 0 ... spritesTree.count {if touchedNode == spritesTree [index] {spritesTree.removeAtIndex(index)}} – gabrielpf