[英]Countdown timer in cocos2d?
我正在嘗試在cocos2d中創建一個倒數計時器,但我無能為力,想解決這個問題,我的代碼在此之下,也許邏輯是錯誤的,但我無法解決。
-(id) init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init] )) {
CCSprite *background = [CCSprite spriteWithFile:@"backgame.png"];
CGSize size = [[CCDirector sharedDirector] winSize];
[background setPosition:ccp(size.width/2, size.height/2)];
[self addChild: background];
[self schedule:@selector(countDown:)];
}
return self;
}
-(void)countDown:(ccTime)delta
{
CCLabel *text = [CCLabel labelWithString:@" "
fontName:@"BallsoOnTheRampage" fontSize:46];
text.position = ccp(160,455);
text.color = ccYELLOW;
[self addChild:text];
int countTime = 20;
while (countTime != 0) {
countTime -= 1;
[text setString:[NSString stringWithFormat:@"%i", countTime]];
}
}
您的int countTime = 20;
每次聲明自己為20。而且,您的while循環將以系統可以更新CCLabel的速度盡快遞減countTimer。 如果您嘗試執行一個真正的計時器, countDown:
希望在countDown:
時將其遞減。 不在while循環中。
嘗試這個:
@interface MyScene : CCLayer
{
CCLabel *_text;
}
@property (nonatomic, retain) int countTime;
@end
@implementation MyScene
@synthesize countTime = _countTime;
-(id) init {
if( (self=[super init] )) {
CCSprite *background = [CCSprite spriteWithFile:@"backgame.png"];
CGSize size = [[CCDirector sharedDirector] winSize];
[background setPosition:ccp(size.width/2, size.height/2)];
[self addChild: background];
_countTime = 20;
_text = [CCLabel labelWithString:[NSString stringWithFormat:@"%i", self.countTime]
fontName:@"BallsoOnTheRampage" fontSize:46];
text.position = ccp(160,455);
text.color = ccYELLOW;
[self addChild:_text];
[self schedule:@selector(countDown:) interval:0.5f];// 0.5second intervals
}
return self;
}
-(void)countDown:(ccTime)delta {
self.countTime--;
[_text setString:[NSString stringWithFormat:@"%i", self.countTime]];
if (self.countTime <= 0) {
[self unschedule:@selector(countDown:)];
}
}
@end
在countDown中,您的計數始終變為20。
您還應該將其移至您的init:
CCLabel *text = [CCLabel labelWithString:@" "
fontName:@"BallsoOnTheRampage" fontSize:46];
text.position = ccp(160,455); text.color = ccYELLOW; [self addChild:text];
然后,您應該使用:
[self schedule:@selector(countDown:) interval:1.0f];
然后,應該使用CCLabelBMFont而不是CCLabel。 它快得多:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.