2017-12-17 5 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? 

스 와이프 제스처의 특성을 지정하는 상수를 정의하십시오. 이러한 상수를 변경하면 스 와이프, 드래그 또는 플릭 간의 차이를 감지 할 수 있습니다.

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

touchesBegan에서, 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 
} 
관련 문제