2014-12-07 35 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