我想计算滑动手势或拖动手势之间的差值。我想要做的是获得此delta,然后将其用作速度(通过添加时间var)。我真的很困惑我应该怎么做 - 通过touchesMoved
或UIPanGestureRecognizer
。另外,我不太了解它们之间的区别。现在我设置并在屏幕上第一次触摸,但我不知道如何获得最后一个,所以我可以计算向量。谁能帮助我?
现在我通过touchesBega
n和touchesEnded
这样做了,我不确定它是否正确且更好,这是我的代码到目前为止:< / p>
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))
}
答案 0 :(得分: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
}