如何获得滑动/拖动触摸的增量

问题描述 投票:1回答:1

我想计算滑动手势或拖动手势之间的差值。我想要做的是获得此delta,然后将其用作速度(通过添加时间var)。我真的很困惑我应该怎么做 - 通过touchesMoved或通过UIPanGestureRecognizer。另外,我真的不明白它们之间的区别。现在我设置并在屏幕上第一次触摸,但我不知道如何获得最后一个,所以我可以计算向量。任何人都可以帮助我吗?

现在我通过touchesBegan和touchesEnded这样做,我不确定它是否正确和更好的方式,这是我的代码到目前为止:

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))
}
swift sprite-kit touch uipangesturerecognizer
1个回答
1
投票

您可以使用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中,存储初始触摸的起点和时间

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

touchesEnded中,计算手势的距离,持续时间和速度。将这些值与常量进行比较,以确定手势是否为滑动。

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
}
© www.soinside.com 2019 - 2024. All rights reserved.