Multi-touch gesture in Sprite Kit
Solution 1:
Moving multiple nodes simultaneously is fairly straightforward. The key is to track each touch event independently. One way to do that is to maintain a dictionary that uses the touch event as the key and the node being moved as the value.
First, declare the dictionary
var selectedNodes:[UITouch:SKSpriteNode] = [:]
Add each sprite touched to the dictionary with the touch event as the key
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in:self)
if let node = self.atPoint(location) as? SKSpriteNode {
// Assumes sprites are named "sprite"
if (node.name == "sprite") {
selectedNodes[touch] = node
}
}
}
}
Update the positions of the sprites as needed
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in:self)
// Update the position of the sprites
if let node = selectedNodes[touch] {
node.position = location
}
}
}
Remove the sprite from the dictionary when the touch ends
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
if selectedNodes[touch] != nil {
selectedNodes[touch] = nil
}
}
}