我有一个移动的精灵,我正在寻找一种方法来获取自上一帧以来的x移动量。这样就可以更新新位置,并且可以获得下一帧的x移动量。有谁知道我怎么能这样做?
我知道我可以写:
override func update(currentTime: NSTimeInterval) {
print(player.position.x)
}
获取当前的x位置。
答案 0 :(得分:1)
为您的班级添加一个变量,例如var lastPlayerPosition: CGPoint?
在更新区块中,获取玩家当前位置,将其与lastPlayerPosition进行比较,然后更新lastPlayerPosition。
然后比较CGPoints以移动距离。
var xDistance: CGFloat = 0.0
var distance: CGFloat = 0.0
var lastPlayerPosition: CGPoint?
override func update(currentTime: NSTimeInterval) {
if self.lastPlayerPosition == nil {
self.lastPlayerPosition = player.position
return
}
xDistance = fabs(Float(self.lastPlayerPosition.x) - Float(player.position.x))
distance = hypotf(Float(self.lastPlayerPosition.x) - Float(player.position.x),
Float(self.lastPlayerPosition.y) - Float(player.position.y))
print("lastPosition.x: \(self.lastPlayerPosition?.x) | player.position.x: \(player.position.x)")
print("xDistance: \(xDistance) | distance: \(distance)")
self.lastPlayerPosition = player.position
}