【发布时间】:2011-11-19 23:24:35
【问题描述】:
请谁能告诉我如何在 cocos2d 中为 iPhone 实现一个倒数计时器来启动游戏。
我的意思是,按下“播放”时,会出现一个新场景,显示数字“3”、“2”、“1”,然后是“GO!”一词。
【问题讨论】:
标签: iphone objective-c cocos2d-iphone
请谁能告诉我如何在 cocos2d 中为 iPhone 实现一个倒数计时器来启动游戏。
我的意思是,按下“播放”时,会出现一个新场景,显示数字“3”、“2”、“1”,然后是“GO!”一词。
【问题讨论】:
标签: iphone objective-c cocos2d-iphone
来自《cocos2d 最佳实践》:
尽量不要使用 Cocoa 的 NSTimer。而是使用 cocos2d 自己的调度器。
所以这是使用 cocos2d 的调度程序为您的标签设置动画的示例,即使有一些效果。
在@界面中:
int timeToPlay;
CCLabelTTF * prepareLabel;
CCLabelTTF * timeoutLabel;
CCMenu *menu;
在初始化中:
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:)];
...
关于ToPlay:
-(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]]];
}
【讨论】:
init 方法的开头添加if ( self = [super init] ) 块。干杯
如果您需要使用 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
}
}
尚未检查该代码的有效性,但它应该可以让您朝着正确的方向前进!
【讨论】: