2014-10-05 61 views
0

基本上,我想用自定義的手勢製作手機遊戲。該手勢有點像摩擦屏幕,從左到右,從右到左。在iOS中製作摩擦屏幕手勢?

如果手勢從左向右移動,這將調用方法並添加一個點。一旦手勢從右向左摩擦,用戶也可以得到一個點。

但問題是,當我使用滑動手勢識別器時,我必須從屏幕釋放手指,才能調用該方法。如果我只是做揉手勢,我無法調用該方法來添加點。

而是嘗試touchesBegan,touchesMoved方法來檢測手指的位置。然而,touchesMoved會創建很多點來與起點進行比較,這會導致多次調用方法而不是一次。

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { 
    for touch: AnyObject in touches 
    { 
     self.touchStartPoint = touch.locationInView(self.myView).x 
    } 
} 

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

    for touch: AnyObject in touches 
    { 
     self.touchOffsetPoint = touch.locationInView(self.myView).x - touchStartPoint 

     if tempTouchOffsetPoint < touchOffsetPoint 
     { 
      var xValueIncreaseArray: NSMutableArray = [] 
      xValueIncreaseArray.addObject(touchOffsetPoint) 
      var maxValue: Double = (xValueIncreaseArray as AnyObject).valueForKeyPath("@max.self") as Double 

      println("\(maxValue)") 

      if maxValue - Double (self.touchStartPoint) > 50 
      { 
       println("right") 
      } 

      println("right") 
     } 
     else if tempTouchOffsetPoint > touchOffsetPoint 
     { 
      /* var xValueDecreaseArray: NSMutableArray = [] 
      xValueDecreaseArray.addObject(touchOffsetPoint)*/ 
      println("left") 
     } 
     else if tempTouchOffsetPoint == touchOffsetPoint 
     { 
      println("Remain") 
     } 
     tempTouchOffsetPoint = touchOffsetPoint 
    } 

是否有任何方法來檢測摩擦手勢?每次手指轉向時,它只會調用一種方法爲用戶添加分數?非常感謝!

+0

我相信你正在尋找一個UIPanGestureRecognizer,它會給你一個新的更新,每當手指移動(但是,你將不得不計算的方向)。 – Jsdodgers 2014-10-05 18:21:26

+0

我擔心UIPanGestureRecognizer不能只被調用一次。我試過了,它會被多次調用。 – aniOSlearner 2014-10-06 06:23:35

回答

1

這個工作對我來說:

let deadZone:CGFloat = 10.0 
var previousTouchPoint: CGFloat! 
var isMovingLeft:Bool? = nil 

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { 
    let point = touches.anyObject()?.locationInView(self) 

    if let newPoint = point?.x { 

     if previousTouchPoint == nil { 
      println("Started") 
      previousTouchPoint = newPoint 
     } else { 

      // Check if they have moved beyond the dead zone 
      if (newPoint < (previousTouchPoint - deadZone)) || (newPoint > (previousTouchPoint + deadZone)) { 

       let newDirectionIsLeft = newPoint < previousTouchPoint 

       // Check if the direction has changed 
       if isMovingLeft != nil && newDirectionIsLeft != isMovingLeft! { 
        println("Direction Changed: Point") 
       } 

       println((newDirectionIsLeft) ? "Moving Left" : "Moving Right") 

       isMovingLeft = newDirectionIsLeft 
       previousTouchPoint = newPoint 
      } 

     } 

    } 
} 

override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) { 
    previousTouchPoint = nil 
    isMovingLeft = nil 
} 

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { 
    previousTouchPoint = nil 
    isMovingLeft = nil 
}