arrays - 从数组 spritekit swift 中删除节点

标签 arrays swift skspritenode removeclass

我正在为 iOS (spritekit/swift) 开发一个小游戏。

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

var spritesTree = [SKSpriteNode]()

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

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

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

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

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

    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)

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

最佳,

最佳答案

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

spritesTree[index].name = String(index) 

当你检查 node touched 之后,你将 name 转换为 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)

关于arrays - 从数组 spritekit swift 中删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39590201/

相关文章:

ios - 快速将目标添加到 UITextView 和 UILabel

ios - 从电话号码中查找国家代码

ios - 如何根据分数更改 SKSpriteNode?

java - 将具有随机行数的字符串保存到单行数组JAVA

java - 有没有一种简单的方法可以将项目列表输入数组,比如 50-100?

c - 二维数组内存分配和传递给函数

ios - 如何找出 NSData 数组的长度?

arrays - SAS如何使用ARRAY更改变量(列)位置(值也)

ios - SpriteKit 动画因 validateIndexBuffer 而崩溃

arrays - 如何使用 Swift 创建一个 SKSpriteNodes 数组?