Calculating delta in SpriteKit using Swift

瘦欲@ 提交于 2020-02-22 06:04:43

问题


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

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