0
\$\begingroup\$

How would one create score dependent on total time in game? I would like the score to count by 1000+ each second the game is running for. Later I am going to add some coins which will give my total score +1000 also.

How would one create this functionality? This is all I have right now:

  let scoreDisplay = UILabel()
    scoreDisplay.text = "Score: \(self.score)"
    scoreDisplay.textColor = UIColor.red
    scoreDisplay.frame = CGRect(x: mainWidth / 2 - 200, y: mainHeight - 400, width: 247, height: 100)
    self.view.addSubview(scoreDisplay)


    let delay = SKAction.wait(forDuration: 0.25)
    let incrementScore = SKAction.run ({
        self.score = self.score + 1
        self.scoreDisplay.text = "\(self.score)"
    })

I'm pretty new to Swift, so sorry for my basic question!

\$\endgroup\$
  • \$\begingroup\$ First you need to have a timer variable that only starts counting when the game has started. some programming languages have build-in timers, but those usually already starts when the application is running (depends if you've a main menu, or reset option). once you've that timer variable, you can use that to count up the score. \$\endgroup\$ – Steven Jan 11 at 14:01
  • 1
    \$\begingroup\$ @Steven that looks to me like the start of a good answer! Care to flesh it out as an answer post? \$\endgroup\$ – DMGregory Jan 11 at 14:34
  • \$\begingroup\$ @Steven thanks for the reply, if you could please give me some code relating to mine, that would seriously help me a lot! Thank you :) \$\endgroup\$ – JimmyK1 Jan 11 at 14:54
1
\$\begingroup\$

First you need to have a timer variable that only starts counting when the game has started.
Some programming languages have build-in timers, but those usually already starts when the application is running, so these aren't useful if you're using a startup screen or reset button. But you can use these timers to calculete the time spend in a timer variable. Once you've that timer variable, you can use that to count up the score.

I'm not familiar with Swift, So I cannot give you a working example. nor do I know if a build-in variable is available.
But you can set a timer variable on your own, similair as how you've defined your scoreDisplay, then add +1 everytime the code gets past the timer variable. problem is however that it calculates in code-ticks, instead of seconds, and it may not be accurate in case of a frame drop.
Other possibilities are to set the current date and time at the moment your game starts, and set the current date and time when the game ends. then substract the ending datetime with your first datetime to get the total time spend.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.