2015-05-14 25 views
0

我在做一个cocos2d项目,我完全是新手。所以请耐心等待。Cocos2d:如何创建一个全局定时器?

当在游戏中创建一个计时器,将在整个应用程序中使用。

-(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--; 

} 

显然,当我点击游戏转到另一个视图时,onEnter被再次调用,触发计时器再次计数。

所以我的问题是我应该如何处理这个问题,使计时器继续相同的计数,即使我在不​​同的意见,像2分钟。

如果它是纯粹的iOS应用程序,我想过2个选项。第一个是通过segue,第二个是使用UserDefaults。

但是我不认为它对于cocos2d是一样的。也没有赛格!

任何意见将不胜感激。谢谢。

+1

你需要使用单例类 –

+1

http://stackoverflow.com/questions/29287968/calculate-the-time-between-the-switches-of-a-view-controller-and-another-view-co/29288656#29288656 –

+0

是唯一的方法吗?我也想过。你可以使用后台线程吗? – tipsywacky

回答

2

请勿使用NSTimer。请使用传递给update:方法的增量时间。

@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; 
    } 
} 

这是一个重复超时;您将需要另一个变量来处理单次超时。

+0

好吧,让我试试这种方法。这种方式很干净。还有一件事。为什么你们使用接口{CGFloat _timeout; }而不是声明一个属性? – tipsywacky

+1

保持它完全私人化,使得实现之外的类难以触及价值。 – trojanfoe

+0

好吧,所以没有优先考虑它大声笑。因为我大多接受过在本机应用程序中使用财产的培训。我看到很多cocos2d示例都使用局部变量。 – tipsywacky

相关问题