iosswiftxcoderemovechildaddchild

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


I have multiple SpriteNodes loaded in my GameScene at random locations, but it is actually the same SpriteNode added multiple times. I have a function in touchesEnded, that removes a SpriteNode once the touch is released on the same location as the SpriteNode. This only works for the initial SpriteNode (the first SpriteNode that was added) but does not work for all the other SpriteNodes.

I tried to turn the code "if object.contains(location)" into a while loop, so that it would repeat for ever touch. That didn't work either.

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()
            }

        }

    }

I expected that whenever I touch an object it would disappear. But that only happens with one object, and it works perfectly fine and as expected with the first object, but the other nine objects show no reaction.


Solution

  • Ok this is the basics of using an array to track the spawned objects so that you can check them all:

    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)
            }
        }
    
    }
    

    Note: that's not the best way to do this for especially from a performance point of view but it's enough to get the idea across.