2014-12-07 36 views
5

我正在使用XCode 6的Sprite-Kit工作在Swift中,而且我有很多不同的节点,但目前我只能设法检测一个手指并同时移动一个节点。 我想知道如何设法检测多个手指以同时移动多个节点。 我实际的代码是:Sprite Kit中的多点触控手势

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 
} 

正如你看到的我只有我的第一根指头的position,但我怎么能检测多个手指的位置和每个手指分配给通过手指触摸的节点?

回答

9

同时移动多个节点相当简单。关键是要独立跟踪每个触摸事件。一种方法是维护一个字典,该字典使用触摸事件作为键并将节点作为值移动。

首先,声明字典

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

添加每个精灵触及到字典中与触摸事件的关键

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

更新精灵的位置根据需要

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

当触摸结束时从字典中移除精灵

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

谢谢。这很好。 – Epsilon 2014-12-10 07:57:42