问题
I am attempting to learn swift by refactoring one of my old games and I need to rewrite my update
method which calculates a delta time. This code works but is ugly. How would I go about properly rewriting this?
import SpriteKit
class GameScene: SKScene {
var lastUpdateTimeInterval: CFTimeInterval?
override func update(currentTime: CFTimeInterval) {
var delta: CFTimeInterval?
if let luti = lastUpdateTimeInterval {
delta = currentTime - luti
} else {
delta = currentTime
}
lastUpdateTimeInterval = currentTime;
if (delta > 1.0) {
delta = minTimeInterval;
lastUpdateTimeInterval = currentTime;
}
updateWithTimeSinceLastUpdate(delta!)
}
}
回答1:
This question belongs to codereview. But I just post answer here and hope it will be migrate to the correct place along with the question.
You have some redundant code, this is my first iteration re-write
class GameScene: SKScene {
var lastUpdateTimeInterval: CFTimeInterval?
override func update(currentTime: CFTimeInterval) {
var delta: CFTimeInterval = currentTime // no reason to make it optional
if let luti = lastUpdateTimeInterval {
delta = currentTime - luti
}
lastUpdateTimeInterval = currentTime
if delta > 1.0 {
delta = minTimeInterval
// this line is redundant lastUpdateTimeInterval = currentTime
}
updateWithTimeSinceLastUpdate(delta)
}
}
and further simplified
class GameScene: SKScene {
var lastUpdateTimeInterval: CFTimeInterval = 0
override func update(currentTime: CFTimeInterval) {
var delta: CFTimeInterval = currentTime - lastUpdateTimeInterval
lastUpdateTimeInterval = currentTime
if delta > 1.0 {
delta = minTimeInterval
}
updateWithTimeSinceLastUpdate(delta)
}
}
You can replace the if
with ?:
, but some people just hate it for some reason
updateWithTimeSinceLastUpdate(delta > 1.0 ? minTimeInterval : delta)
来源:https://stackoverflow.com/questions/24728881/calculating-delta-in-spritekit-using-swift