如果您之前玩过Agar.io,那么您可能会熟悉摄像机移动的方式。它会根据鼠标距离屏幕中心的距离向鼠标滑动。我正在尝试使用SKCameraNode和touchesMoved来重新创建这种运动。
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let pos = touches.first!.location(in: view)
let center = view!.center
let xDist = pos.x - center.x
let yDist = pos.y - center.y
let distance = sqrt((xDist * xDist) + (yDist * yDist)) * 0.02
camera?.position.x += xDist * distance * 0.02
camera?.position.y -= yDist * distance * 0.02
}
出人意料的是,这看起来并不太糟。但是,它有两个问题。
第一个问题是我想使用UIPanGestureRecognizer,因为它可以更好地处理多点触摸。但我无法想象如何实现它,因为我想不出如何使用它获取从触摸到屏幕中心的距离。
第二个问题是移动不够流畅。如果用户停止手指移动一帧,相机会突然停止,导致巨大的跳跃。由于我的数学很差,所以我无法想到一种实现平滑衰减(或攻击)的好方法。
任何帮助都将是极好的!
编辑:我现在正在做这个:
private var difference = CGVector()
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let pos = touches.first!.location(in: view)
let center = view!.center
difference = CGVector(dx: pos.x - center.x, dy: pos.y - center.y)
}
override func update(_ currentTime: TimeInterval) {
let distance = sqrt((difference.dx * difference.dx) + (difference.dy * difference.dy)) * 0.02
camera?.position.x += difference.dx * distance * 0.02
camera?.position.y -= difference.dy * distance * 0.02
}
现在我需要知道一个好的方法,让差异变量从用户触摸屏幕的时间开始平稳增加。
编辑 2:现在我正在做这个:
private var difference = CGVector()
private var touching: Bool = false
private var fade: CGFloat = 0
private func touched(_ touch: UITouch) {
let pos = touch.location(in: view)
let center = view!.center
difference = CGVector(dx: pos.x - center.x, dy: pos.y - center.y)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
touching = true
touched(touches.first!)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
touched(touches.first!)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
touching = false
touched(touches.first!)
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
touching = false
}
override func update(_ currentTime: TimeInterval) {
if touching {
if fade < 0.02 { fade += 0.0005 }
} else {
if fade > 0 { fade -= 0.0005 }
}
let distance = sqrt((difference.dx * difference.dx) + (difference.dy * difference.dy)) * 0.01
camera?.position.x += difference.dx * distance * fade
camera?.position.y -= difference.dy * distance * fade
}
在这变得更糟之前,能有人帮我一下吗?fade变量以一种可怕的方式递增,并且不够平滑,我只需要有人给我一个更好的提示来解决它。