2015-08-25 90 views
1

我想創建一個iOS遊戲,我有它,所以當物品被觸摸和移動它被拖動。當它被拖動時,鼠標被捕捉到精靈的中心。我怎麼能這樣做,這不會發生?SpriteKit - 鼠標捕捉中心在精靈拖動

Here是發生了什麼事情的一個例子。

這裏有處理觸摸輸入

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { 

    var papers = 0 

    for touch in (touches as! Set<UITouch>) { 
     let location = touch.locationInNode(self) 
     let touchedNode = nodeAtPoint(location) 

     if ((touchedNode.name?.contains("paper")) != nil) { 

      touchedNode.position = location 
      touchedNode.position.x = CGRectGetMidX(self.frame) 
     } 
    } 
} 
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { 
     for touch: AnyObject in touches { 
      let location = touch.locationInNode(self) 
      let touchedNode = nodeAtPoint(location) 

      if ((touchedNode.name?.contains("paper")) != nil) { 

       touchedNode.position = location 
       touchedNode.position.x = CGRectGetMidX(self.frame) 
      } 
     } 
    } 

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { 
    for touch: AnyObject in touches { 
     let location = touch.locationInNode(self) 
     let touchedNode = nodeAtPoint(location) 
     if ((touchedNode.name?.contains("paper")) != nil) { 
      touchedNode.zPosition = 0 
      touchedNode.position.x = CGRectGetMidX(self.frame) 
     } 
    } 
} 

P.S.功能contains是String類的擴展,用於檢查子串是否在字符串中

在此先感謝!

回答

1

將sprite從觸摸位置而不是從sprite的中心拖出很簡單。爲此,計算並存儲觸摸位置和精靈中心之間的差異(即偏移量)。然後,在touchesMoved中,將精靈的新位置設置爲觸摸位置加上偏移量。

您可以選擇性地重載+-運算符,以簡化加減運算CGPoint s。定義該GameScene類以外:

func - (left:CGPoint,right:CGPoint) -> CGPoint { 
    return CGPoint(x: right.x-left.x, y: right.y-left.y) 
} 

func + (left:CGPoint,right:CGPoint) -> CGPoint { 
    return CGPoint(x: right.x+left.x, y: right.y+left.y) 
} 

在GameScene,定義下面的實例變量

var offset:CGPoint? 

,然後在touchesBegan,取代

touchedNode.position = location 

offset = location - touchedNode.position 

和在touchesMoved,取代

touchedNode.position = location 

if let offset = self.offset { 
    touchedNode.position = location + offset 
} 

予廣義的溶液,以抵消在xy尺寸既精靈的位置。在你的應用中,你可以簡單地抵消精靈y的位置,因爲x被忽略。

+0

非常感謝!我被困在這一段時間了! – TimmyO18

1

你不需要touchesBegan和touchesEnded這個。你可以使用touchesMoved:

for touch: AnyObject in touches { 
     let location = touch.locationInNode(self) 
     let touchedNode = nodeAtPoint(location) 
     let previousPosition = touch.previousLocationInNode(self) 

     if (touchedNode.name == "paper") { 

      var translation:CGPoint = CGPoint(x: location.x - previousPosition.x , y: location.y - previousPosition.y) 

      touchedNode.position = CGPoint(x: touchedNode.position.x , y: touchedNode.position.y + translation.y) 


     } 
    } 

這個想法是計算翻譯。您可以閱讀更多關於此解決方案here。對於未來的讀者,可以在StackOverflow找到Obj-C解決方案on this link