Calculating delta in SpriteKit using Swift

空扰寡人 提交于 2019-12-06 04:27:29
Bryan Chen

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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!