Multi-Touch Gesture in Sprite Set

I work in Swift using the Sprite-Kit using Xcode 6, and I have many different nodes, but at the moment I can only detect one finger and move one node at a time. I want to know how I managed to detect several fingers in order to move several nodes at the same time. My actual code is:

var location = CGFloat() // finger position var actualNode = -1 // node touched by the finger, -1 means no node touched override func touchesBegan(touches: NSSet, withEvent event: UIEvent) // when a finger touch the screen { for touch: AnyObject in touches { location = touch.locationInNode(self) // we detect the finger position } for var index = 0; index < colorNode.count; index++ { if nodeAtPoint(location) == colorNode[index].node { actualNode = index // the number of the node touched by the finger } } } override func touchesMoved(touches: NSSet, withEvent event: UIEvent) // when a finger move { for touch: AnyObject in touches { location = touch.locationInNode(self) // we detect the finger position } if actualNode != -1 // if a node is touched { colorNode[actualNode].position = location // we move this node to the finger } } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) // when a finger don't touch the screen anymore { actualNode = -1 // there is no node touched } 

As you can see, I only have the position my first finger, but how can I detect multiple finger positions and assign each finger to the node touched by the finger?

+5
source share
2 answers

Moving multiple nodes at the same time is quite simple. The key is to track each touch event independently. One way to do this is to maintain a dictionary that uses a touch event when a key and node move as a value.

Declare a dictionary first

 var selectedNodes:[UITouch:SKSpriteNode] = [:] 

Add each dictionary sprite using a touch event as a 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 sprite position 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 } } } 

Extract sprite from dictionary when touch ends

 override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { if selectedNodes[touch] != nil { selectedNodes[touch] = nil } } } 
+10
source

Do not forget to install

  skView.isMultipleTouchEnabled = true 

Then follow the instructions above

Moving multiple nodes at the same time is quite simple. The key is to track every touch event independently ......

0
source

Source: https://habr.com/ru/post/1208531/


All Articles