如何使 'removeFromParent()' 工作多次?

How to make 'removeFromParent()' work multiple times?

我在 GameScene 中的随机位置加载了多个 SpriteNode,但实际上是同一个 SpriteNode 添加了多次。我在 touchesEnded 中有一个函数,一旦在与 SpriteNode 相同的位置释放触摸,它就会删除 SpriteNode。这仅适用于初始 SpriteNode(添加的第一个 SpriteNode),但不适用于所有其他 SpriteNode。

我试图将代码 "if object.contains(location)" 变成一个 while 循环,这样它就可以重复 for ever touch。那也没用。

var object = SKSpriteNode()
var objectCount = 0


func spawnObject() {

        object = SKSpriteNode(imageNamed: "image")
        object.position = CGPoint(x: randomX, y: randomY)
        objectCount = objectCount + 1
        self.addChild(object)

}


while objectCount < 10 {

        spawnObject()

}


override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

        for t in touches {

            let location = t.location(in: self)

            if object.contains(location) {
                object.removeFromParent()
            }

        }

    }

我原以为只要我触摸一个物体它就会消失。但这只发生在一个物体上,并且它工作得很好并且与第一个物体的预期一样,但其他九个物体没有反应。

好的,这是使用数组跟踪生成对象的基础知识,以便您可以检查所有对象:

var objectList: [SKSpriteNode] = [] // Create an empty array


func spawnObject() {

    let object = SKSpriteNode(imageNamed: "image")
    object.position = CGPoint(x: randomX, y: randomY)
    self.addChild(object)

    objectList.append(object) // Add this object to our object array

}

while objectList.count < 10 {

spawnObject()

}


override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

    for t in touches {

        let location = t.location(in: self)

        // Check all objects in the array
        for object in objectList {
            if object.contains(location) {
                object.removeFromParent()
            }
        }
        // Now remove those items from our array
        objectList.removeAll { (object) -> Bool in
            object.contains(location)
        }
    }

}

注意:这不是最好的方法,尤其是从性能的角度来看,但足以让这个想法得到理解。