cocos2d:如何设置定时器

5

我正在使用cocos2d和box2d开发iPhone应用程序。在这个应用程序中,我需要设置一个计时器。 计时器将显示玩家到达目的地剩余的时间......

我该如何做呢?我已经绘制了场景,但是作为初学者,不确定如何添加计时器......

谢谢

2个回答

18

我会简单地使用定时器来实现。这适用于所有基于CCNode的类。

每秒调用一次的定时器:

[self schedule:@selector(timerUpdate:) interval:1];

这个方法每秒钟被调用一次:

-(void) timerUpdate:(ccTime)delta
{
  numSeconds++;
  // update timer here, using numSeconds
}

Parceval 的方法使用 CCTimer 也可以,但你应该更喜欢这样的静态自动释放初始化器:

CCTimer *myTimer = [CCTimer timerWithTarget:self
                                   selector:@selector(myTimedMethod:)
                                   interval:delay]];

这个方法在v2.x中出现问题。有什么替代方法吗?虽然头文件包含该方法,但Xcode会出现错误。 - Pawan Sharma
一样的情况。在iOS 7.1和Xcode 5.1.1中,已经没有timerWithTarget或initWithTarget方法了。 - MB_iOSDeveloper

6
你可以使用CCTimer。 就像这样:
float delay = 1.0; // Number of seconds between each call of myTimedMethod:
CCTimer *myTimer = [[CCTimer alloc] initWithTarget:self 
                             selector:@selector(myTimedMethod:) interval:delay]];

每秒钟都会调用 myTimedMethod: 方法。


CCTimer相对于NSTimer有何优势? - Jacob Relkin
它使用cocos2d的内部调度机制。如果我理解正确,它取决于使用哪种CCDirector类型。在这种情况下,优缺点(如果有的话)可能大多不相关。 - CodeSmile
8
一个很大的优点是,当游戏暂停时,这个计时器也会被暂停。 - Thomas Kekeisen
1
它保证在更新/渲染循环中的特定时间触发。 - CodeSmile

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接