Reputation: 103
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
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 }
}
}
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)
Now you can remove all the linked nodes of a given node writing
LinkedNodes.shared.removeNodesLinked(to: original)
Upvotes: 2
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