tipsywacky
tipsywacky

Reputation: 3464

Cocos2d: How to create a global timer?

I'm doing a cocos2d project which I'm completely newbie in. So please bear with me.

When creating a timer in the game that will be use throughout the app.

-(void)onEnter
{
    [super onEnter];
    [self.timerCountDown invalidate];


        self.timerCountDown = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerCountDown:) userInfo:nil repeats:YES];

}

-(void) timerCountDown: (NSTimer*) timer {

    self.secondsLeft--;

}

Apparently when I click the game to go to another view, the onEnter got called again that triggers the timer to count again.

So my question is how should I approach this problem to make the timer continues the same counts even I'm in a different views for like 2 mins.

If it is purely iOS app, I thought about 2 options. First one is pass through segue and second one is to use UserDefaults.

However I don't think it is the same for cocos2d. There is no segue as well!

Any advice will be grateful. Thanks.

Upvotes: 0

Views: 343

Answers (1)

trojanfoe
trojanfoe

Reputation: 122401

Don't use NSTimer. Instead use the delta times passed to the update: method.

@interface YourClass ()
{
    CGFloat _timeout;
}
@end

@implementation YourClass

-(void)onEnter
{
    [super onEnter];
    _timeout = 30.0;
}

- (void)update:(CCTime)deltaTime
{
    _timeout -= deltaTime;
    if (_timeout < 0.0) {
        // Do thing
        _timeout = 30.0;
    }
}

That is a repeating timeout; you'll need another variable for a single-shot timeout.

Upvotes: 2

Related Questions