memyselfandmyiphone
memyselfandmyiphone

Reputation: 1110

Countdown in Cocos2d

I am trying to think through how to implement a countdown on a stamina level. For example, maximum 100% and over time it decreases. I don't need to know how to display it but the technology behind it to get it working and where to look.

This countdown would keep on going down when the application is closed.

I was looking at NSUserDefaults as a means to do this. Is this correct?

Similar to the top bar as shown below: enter image description here

Upvotes: 0

Views: 111

Answers (1)

Insomniac
Insomniac

Reputation: 3384

You can save latest refueled stamina value in NSUserDefaults or in iCloud and calculate current value using something like this:

timePassedInSeconds = currentTime - latestMaxValueSaveTime;  
newStamina = latestMaxValue - (timePassedInSeconds * decreasePerSecond);

This way each time the player refuels stamina (e.g. buys some food for animal) you reset stamina to 100% (or add some percentage depending on food type) and save this value into latestMaxValue and save the time it was refueled into latestMaxValueSaveTime (you can store both in NSUserDefaults)

And you calculate newStamina in update: of the scene or in onEnter: method of the scene if it needs to be calculated once.

This way it will decrease even when the app is closed.

However, if you want to avoid players resetting stamina by changing device time you should get time from the server (preferably in UTC, to avoid issues with timezones and daylight saving).

Upvotes: 1

Related Questions