2015-10-15 46 views
0

我在SpriteKit中製作遊戲。我在那裏有一個左邊的街區和一個右邊的街區。起初我以爲使用nodeAtPoint與塊進行交互,但在我的情況下,對於玩家來說太不舒服。我想這樣做,如果玩家觸摸屏幕左側的任何地方 - 它會觸發左側屏蔽,屏幕右側會相應地觸發右側屏蔽。一個人怎麼能這樣做呢? 現在我使用節點點交互的代碼如下所示:如何在視圖中設置觸摸位置

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { 
    /* Called when a touch begins */ 
    for touch: AnyObject in touches { 
     let location = touch.locationInNode(self) 
     switch self.nodeAtPoint(location) { 
     case self.leftblock: 
      println("closeleft") 
      leftblock.runAction(SKAction.animateWithTextures(leftArray, timePerFrame: 0.03, resize: true, restore: false)) 
     case self.rightblock: 
      println("closeright") 
      rightblock.runAction(SKAction.animateWithTextures(rightArray, timePerFrame: 0.03, resize: true, restore: false)) 
     default: break 
     } 
    } 
} 


override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { 
    /* Called when a touch begins */ 
    for touch: AnyObject in touches { 
     let location = touch.locationInNode(self) 
     switch self.nodeAtPoint(location) { 
     case self.leftblock: 
      println("openleft") 
      leftblock.runAction(SKAction.animateWithTextures(reversedLeftArray, timePerFrame: 0.03, resize: true, restore: false)) 
     case self.rightblock: 
      println("openright") 
      rightblock.runAction(SKAction.animateWithTextures(reversedRightArray, timePerFrame: 0.03, resize: true, restore: false)) 
     default: break 
     } 
    } 
} 

回答

0

在屏幕左側的觸摸意味着該x coordinate of the location of the touch將小於width/2。而對於右側, 的x coordinate of the location of the touch將大於width/2

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { 

    for touch in touches { 

     let touchPoint = touch.locationInView(self.view) 

     let middleOfScreen = (self.view?.frame.width)!/2 

     print(self.frame) 

     print(middleOfScreen) 
     print(touchPoint) 

     if touchPoint.x < middleOfScreen { 
      print("Clicked Left Side"); 
     } else { 
      print("Clicked Right Side"); 
     } 
    } 
} 
+0

謝謝!這就是我的預期! :) – TimurTim