2015-03-02 107 views
0
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { 

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

      var translation = CGPointMake(location.x - previousLocation.x, location.y - previousLocation.y) 
crossHair.position = CGPointMake(crossHair.position.x + translation.x * 3, crossHair.position.y + translation.y * 3) 
    } 
    } 

我在屏幕上有一個十字準線,我可以使用touchesmoved如上所示移動它,但是我的問題是我不知道如何防止它進入屏幕。有fmaxf & fminf但我不完全確定如何使用它們,任何幫助將不勝感激。鉗位節點到屏幕邊界

回答

1

您可以使用以下代碼將node限制在座標內。以下代碼僅檢查精靈的位置是否在邊界內。我認爲這個位置在精靈的中心。

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { 

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

     var translation = CGPointMake(location.x - previousLocation.x, location.y - previousLocation.y) 
     var positionX : CGFloat = crossHair.position.x + translation.x * 3 
     var positionY : CGFloat = crossHair.position.y + translation.y * 3 

     if positionX < 0 { 
      positionX = 0 
     } 
     else if positionX > self.size.width 
     { 
      positionX = self.size.width 
     } 

     if positionY < 0 { 
      positionY = 0 
     } 
     else if positionY > self.size.height 
     { 
      positionY = self.size.height 
     } 

     crossHair.position = CGPointMake(positionX, positionY) 

    } 
} 
+1

謝謝你,完美的作品。 – Abdou023 2015-03-02 13:44:22

1

獲得十字線的位置後,檢查它是否不被外部屏幕:

var x = crossHair.position.x; 
var y = crossHair.position.y; 
if(crossHair.position.x > self.size.width) { 
    x = self.size.width; 
} 
if(crossHair.position.x < 0) { 
x = 0; 
} 
if(crossHair.position.y > self.size.height) { 
    y = self.size.height; 
} 
if(crossHair.position.y < 0) { 
y = 0; 
} 

crossHair.position = CGPointMake(x,y); 
+0

謝謝,完美的作品。 – Abdou023 2015-03-02 13:44:38