gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:07:12 25 4
gpt4 key购买 nike

我想计算滑动手势或拖动手势之间的增量。我想要做的是获得这个增量,然后将其用作速度(通过添加时间变量)。我真的很困惑我应该怎么做 - 通过 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))
}

最佳答案

您可以使用 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
}

关于swift - 如何获得滑动/拖动触摸的增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47856682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com