我正在做一个 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--;
}
显然,当我单击游戏转到另一个 View 时,再次调用 onEnter 触发计时器再次计数。
所以我的问题是我应该如何解决这个问题,使计时器继续相同的计数,即使我在不同的 View 中持续 2 分钟。
如果它是纯粹的 iOS 应用程序,我考虑了 2 个选项。第一个是通过 segue,第二个是使用 UserDefaults。
不过我觉得cocos2d不一样。也没有 segue!
如有任何建议,我们将不胜感激。谢谢。
最佳答案
不要使用 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;
}
}
那是重复超时;您将需要另一个变量来设置单次超时。
关于ios - Cocos2d : How to create a global timer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30240446/