在我的游戏中,玩家 Sprite 连续向上移动,因为我在更新函数中设置了 Sprite 的速度:
override func update(_ currentTime: TimeInterval) {
...
player.physicsBody!.velocity.dy = max(player.physicsBody!.velocity.dy, 650 * gameGain)
}
现在我想测量 Sprite 走过的总距离。有什么方法/方法可以这样做,还是我必须创建一个变量来手动计算距离,例如
var distance:Float
override func update(_ currentTime: TimeInterval) {
player.physicsBody!.velocity.dy = max(player.physicsBody!.velocity.dy, 650 * gameGain)
distance += 650
}
提前致谢!
最佳答案
如果你对起始位置到当前位置的距离感兴趣,可以记住起始位置,然后计算距离:
let startPosition: CGPoint
var distance: CGFloat
init(startLocation: CGPoint) {
self.startPosition = startPosition
distance = 0
}
// Calculate the distance between two points using Pythagoras. You can make your code clean, by moving this into an extension for CGPoint.
private func distance(point1: CGPoint, point1: CGPoint) -> CGFloat {
let dx = point1.x - point2.x
let dy = point1.y - point2.y
return sqrt(dx * dx + dy * dy);
}
override func update(_ currentTime: TimeInterval) {
// Move the sprite
let newPlayerPosition = player.position
distance = distance(point1: newPlayerPosition, point2: startPosition)
}
关于ios - Swift 和 Sprite Kit - 如何测量 Sprite 移动的总距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53394005/