SpriteKit - Creating a timer

前端 未结 5 1944
小鲜肉
小鲜肉 2020-11-22 05:15

How can I create a timer that fires every two seconds that will increment the score by one on a HUD I have on my screen? This is the code I have for the HUD:



        
5条回答
  •  我寻月下人不归
    2020-11-22 05:18

    Here's the full code to build a timer for SpriteKit with Xcode 9.3 and Swift 4.1

    In our example the score label will be incrementd by 1 every 2 seconds. Here's final result

    Good, let's start!

    1) The score label

    First of all we need a label

    class GameScene: SKScene {
        private let label = SKLabelNode(text: "Score: 0")
    }
    

    2) The score label goes into the scene

    class GameScene: SKScene {
    
        private let label = SKLabelNode(text: "Score: 0")
    
        override func didMove(to view: SKView) {
            self.label.fontSize = 60
            self.addChild(label)
        }
    }
    

    Now the label is at the center of the screen. Let's run the project to see it.

    Please note that at this point the label is not being updated!

    3) A counter

    We also want to build a counter property which will hold the current value displayed by the label. We also want the label to be updated as soon as the counter property is changed so...

    class GameScene: SKScene {
    
        private let label = SKLabelNode(text: "Score: 0")
        private var counter = 0 {
            didSet {
                self.label.text = "Score: \(self.counter)"
            }
        }
    
        override func didMove(to view: SKView) {
            self.label.fontSize = 60
            self.addChild(label)
    
            // let's test it!
            self.counter = 123
        }
    }
    

    4) The actions

    Finally we want to build an action that every 2 seconds will increment counter

    class GameScene: SKScene {
    
        private let label = SKLabelNode(text: "Score: 0")
        private var counter = 0 {
            didSet {
                self.label.text = "Score: \(self.counter)"
            }
        }
    
        override func didMove(to view: SKView) {
            self.label.fontSize = 60
            self.addChild(label)
            // 1 wait action
            let wait2Seconds = SKAction.wait(forDuration: 2)
            // 2 increment action
            let incrementCounter = SKAction.run { [weak self] in
                self?.counter += 1
            }
            // 3. wait + increment
            let sequence = SKAction.sequence([wait2Seconds, incrementCounter])
            // 4. (wait + increment) forever
            let repeatForever = SKAction.repeatForever(sequence)
    
            // run it!
            self.run(repeatForever)
        }
    }
    

提交回复
热议问题