Hello, I am developing a 2d iphone game by using cocos2d. I need a countdown timer. Plz tell me, How can I create a count down Timer in cocos2d ?
A:
Look at NSTimer, it can most likely provide any needed timer functionality.
Joel Levin
2009-01-16 05:59:16
A:
Use NSTimer. It will call a method every x seconds (x specified when creating the timer) This example calls the method changeTime every 1 second
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeTime:) userInfo:nil repeats:YES];
-(void)changeTime:(NSTimer *)theTimer{
if(timeLeft==0){
return;
}
else{
timeLeft = timeLeft - 1;
if(timeLeft==0){
[theTimer invalidate];
[self goToNextExercise];
}
}
label.text = [NSString stringWithFormat:@"%i",timeLeft];
}
lostInTransit
2009-01-19 08:58:36
Thanks for ur answer. its working....
Nahid
2009-01-22 10:31:10
This is the wrong way to do this using cocos2d, You need to do what others have said and use the [self schedule:] stuff. The biggest reasons are that using NSTimer will not support cocos2d pause, start, stop commands whild schedule will.
Solmead
2009-06-25 19:46:57
Needs to be said again: DO NOT USE NSTimer! This is WRONG.
Sneakyness
2010-02-10 23:10:39
Reference: http://www.cocos2d-iphone.org/api-ref/latest-stable/interface_timer.html
Sneakyness
2010-02-10 23:11:29
+21
A:
Not enough rep to upvote Tom, but he's absolutely right. Within the context of this question, NSTimer is the WRONG solution. The Cocos2d framework provides a scheduler that integrates with other game features like Pause/Resume (and most likely uses NSTimer under the hood).
Example from the above link:
-(id) init
{
if( ! [super init] )
return nil;
// schedule timer
[self schedule: @selector(tick:)];
[self schedule: @selector(tick2:) interval:0.5];
return self;
}
-(void) tick: (ccTime) dt
{
// bla bla bla
}
-(void) tick2: (ccTime) dt
{
// bla bla bla
}
JustinB
2009-03-03 08:54:17
and similarly use [self unschedule:@selector(tick2:)] inside tick2: when you want it to stop repeating.
adam
2010-04-09 14:57:52
[self schedule: @selector(tick:)];when i try to do it in my code... my application can't find schedule... it is function of which class...?
mihirpmehta
2010-06-03 08:54:36