2017-12-17 10 views
1

スワイプジェスチャまたはドラッグジェスチャの間のデルタを計算したいと思います。私がやりたいことは、このデルタを取得し、速度として(時間varを追加することによって)それを使用することです。 touchesMovedまたはUIPanGestureRecognizerを介して、私はこれをどうすればいいのか分かりません。また、私は実際にそれらの違いを理解していません。今私は画面に最初のタッチを設定して取得するが、私はベクトルを計算することができるように最後のものを取得する方法がわからない。誰もそれで私を助けることができますか?スワイプ/ドラッグタッチのデルタを取得する方法

class GameScene: SKScene { 
var start: CGPoint? 
var end: CGPoint? 


override func didMove(to view: SKView) {   

} 

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    guard let touch = touches.first else {return} 
    self.start = touch.location(in: self) 
    print("start point: ", start!) 
} 

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 
    guard let touch = touches.first else {return} 
    self.end = touch.location(in: self) 
    print("end point: ", end!) 

    let deltax:CGFloat = ((self.start?.x)! - (self.end?.x)!) 
    let deltay:CGFloat = ((self.start?.y)! - (self.end?.y)!) 
    print(UInt(deltax)) 
    print(UInt(deltay)) 
} 

答えて

1

あなたはスワイプのジェスチャーを検出することができます:その権利とより良い方法は、ここではこれまでのところ、私のコードであれば

は、今私がtouchesBega、nおよびtouchesEndedを経て、私はよく分からないことをやっていますSpriteKitの組み込みタッチハンドラを使用するか、UISwipeGestureRecognizerを実装することができます。以下は、SpriteKitベースのタッチ・ハンドラを使用して、スワイプのジェスチャーを検出する方法の例です:

まず、変数や定数を定義...

初期タッチの出発点と時間を定義します。

var touchStart: CGPoint? 
var startTime : TimeInterval? 

スワイプジェスチャの特性を指定する定数を定義します。これらの定数を変更することで、スワイプ、ドラッグ、またはフリックの違いを検出できます。 touchesBegan

let minSpeed:CGFloat = 1000 
let maxSpeed:CGFloat = 5000 
let minDistance:CGFloat = 25 
let minDuration:TimeInterval = 0.1 

、ジェスチャーの距離、所要時間、および速度を計算し、最初のタッチtouchesEnded

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    touchStart = touches.first?.location(in: self) 
    startTime = touches.first?.timestamp 
} 

の出発点と時間を記憶します。これらの値を定数と比較して、ジェスチャーがスワイプかどうかを判断します。

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 
    guard let touchStart = self.touchStart else { 
     return 
    } 
    guard let startTime = self.startTime else { 
     return 
    } 
    guard let location = touches.first?.location(in: self) else { 
     return 
    } 
    guard let time = touches.first?.timestamp else { 
     return 
    } 
    var dx = location.x - touchStart.x 
    var dy = location.y - touchStart.y 
    // Distance of the gesture 
    let distance = sqrt(dx*dx+dy*dy) 
    if distance >= minDistance { 
     // Duration of the gesture 
     let deltaTime = time - startTime 
     if deltaTime > minDuration { 
      // Speed of the gesture 
      let speed = distance/CGFloat(deltaTime) 
      if speed >= minSpeed && speed <= maxSpeed { 
       // Normalize by distance to obtain unit vector 
       dx /= distance 
       dy /= distance 
       // Swipe detected 
       print("Swipe detected with speed = \(speed) and direction (\(dx), \(dy)") 
      } 
     } 
    } 
    // Reset variables 
    touchStart = nil 
    startTime = nil 
} 
関連する問題