How can I make a function execute every second in swift?

后端 未结 7 1797
离开以前
离开以前 2020-11-29 01:59

I want to add a score to the top of my scene in the game I am working on. The score is going to based on how long you last, and will increase every second. Thanks for the he

7条回答
  •  猫巷女王i
    2020-11-29 02:49

    I don't think you need NSTimer for this.

    Since you are using SpriteKit, I am going to suggest simplest solution in my opinion:

    Declare a variable var prevScoreCalcTime:TimeInterval = 0

    Inside of update func in your GameScene set it up like below:

    override func update(_ currentTime: TimeInterval) {
        if currentTime - prevScoreCalcTime > 1 {
            prevScoreCalcTime = currentTime
            // Any function you put here will execute every second
        }
    }
    

    Good luck!

提交回复
热议问题