Johan Kornet
Johan Kornet

Reputation: 103

Copy() node in SpriteKit with Swift

I have made a copy from a node with copy() in Swift

For example:

var copy = original.copy() as! SKSpriteNode) 

and this works fine.

My question is when I want to remove the original node (with removeFromParent) I also want to automatically remove the copy node.

How do I do that? I made a 2D spaceshooter (like Defender) and I used the copy node in the Radarcam.

Thanks.

Upvotes: 1

Views: 1247

Answers (2)

Luca Angeletti
Luca Angeletti

Reputation: 59536

You can define a class like this to keep track of the links between nodes (as suggested by Paulw11).

final class LinkedNodes {

    static let shared = LinkedNodes()
    private var links: [(SKNode, SKNode)] = []

    private init() { }

    func link(nodeA: SKNode, to nodeB: SKNode) {
        let pair = (nodeA, nodeB)
        links.append(pair)
    }

    func removeNodesLinked(to node: SKNode) {
        let linkedNodes = links.reduce(Set<SKNode>()) { (res, pair) -> Set<SKNode> in
            var res = res
            if pair.0 == node {
                res.insert(pair.1)
            }
            if pair.1 == node {
                res.insert(pair.0)
            }
            return res
        }
        linkedNodes.forEach { $0.removeFromParent() }
        links = links.filter { $0.0 != node && $0.1 != node }
    }
}

Copying a node

Now just remember to create a link when you copy a node

let copy = original.copy() as! SKSpriteNode)
LinkedNodes.shared.link(nodeA: original, to: copy)

Removing a node

Now you can remove all the linked nodes of a given node writing

LinkedNodes.shared.removeNodesLinked(to: original)

Upvotes: 2

Knight0fDragon
Knight0fDragon

Reputation: 16837

Very simple solution, make a node to parent both the original and copy, and then just remove the parent when not needed anymore.

Upvotes: 1

Related Questions