Kyle Decot Kyle Decot - 3 years ago 177
Swift Question

Calculating delta in SpriteKit using Swift

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!)
}
}

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download