请有人能告诉我如何实现倒计时器,以便在iPhone的cocos2d中开始游戏。
我的意思是,在按下“播放”时,会出现一个新的场景,显示数字“3”,“2”,“1”,然后是“GO!”。
答案 0 :(得分:3)
来自“cocos2d最佳实践”:
尽量不要使用Cocoa的NSTimer。而是使用cocos2d自己的调度程序。
因此,这是使用cocos2d的调度程序为您的标签设置动画的示例,即使有一些效果。
在@interface中:
int timeToPlay;
CCLabelTTF * prepareLabel;
CCLabelTTF * timeoutLabel;
CCMenu *menu;
在init中:
timeToPlay=4;
CGSize s = [CCDirector sharedDirector].winSize;
prepareLabel = [CCLabelTTF labelWithString:@"Prepare to play!" fontName:@"Marker Felt" fontSize:40];
prepareLabel.position = ccp(s.width/2.0f, 150);
timeoutLabel = [CCLabelTTF labelWithString:@"3" fontName:@"Marker Felt" fontSize:60];
timeoutLabel.position = ccp(s.width/2.0f, 90);
[self addChild:prepareLabel];
[self addChild:timeoutLabel];
timeoutLabel.visible=NO;
prepareLabel.visible=NO;
...
CCMenuItem *Play = [CCMenuItemFont itemFromString:@"PLAY"
target:self
selector:@selector(aboutToPlay:)];
...
aboutToPlay:
-(void) aboutToPlay: (id) sender {
[self removeChild:menu cleanup:YES];
timeoutLabel.visible=YES;
prepareLabel.visible=YES;
[self schedule: @selector(tick:) interval:1];
}
然后打勾:
-(void) tick: (ccTime) dt
{
if(timeToPlay==1) [self play];
else {
timeToPlay--;
NSString * countStr;
if(timeToPlay==1)
countStr = [NSString stringWithFormat:@"GO!"];
else
countStr = [NSString stringWithFormat:@"%d", timeToPlay-1];
timeoutLabel.string = countStr;
//and some cool animation effect
CCLabelTTF* label = [CCLabelTTF labelWithString:countStr fontName:@"Marker Felt" fontSize:60];
label.position = timeoutLabel.position;
[self addChild: label z: 1001];
id scoreAction = [CCSequence actions:
[CCSpawn actions:
[CCScaleBy actionWithDuration:0.4 scale:2.0],
[CCEaseIn actionWithAction:[CCFadeOut actionWithDuration:0.4] rate:2],
nil],
[CCCallBlock actionWithBlock:^{
[self removeChild:label cleanup:YES];
}],
nil];
[label runAction:scoreAction];
}
}
玩:
-(void) play {
[[CCDirector sharedDirector] replaceScene:[CCTransitionSlideInL transitionWithDuration:0.4 scene:[GamePlay node]]];
}
答案 1 :(得分:2)
如果您需要使用cocos2d,请务必执行此操作,但只需执行而不使用即可。在IB中设置具有必要出口的UILabel,将countdownTimer
声明为NSTimer对象,然后在viewDidLoad或其他重要位置声明:
countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
label.text = @"3";
[countdownTimer fire];
然后更新时间:
- (void)updateTime {
if ([label.text isEqualToString:@"3"]) {
label.text = @"2";
} else if ([label.text isEqualToString:@"2"]) {
label.text = @"1";
} else {
label.text = @"GO!";
[countdownTimer invalidate];
//continue with app
}
}
没有检查该代码的有效性,但它应该让你朝着正确的方向前进!