views:

6022

answers:

4

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.

NSTimer class reference

Joel Levin
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
Thanks for ur answer. its working....
Nahid
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
Needs to be said again: DO NOT USE NSTimer! This is WRONG.
Sneakyness
Reference: http://www.cocos2d-iphone.org/api-ref/latest-stable/interface_timer.html
Sneakyness
+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
and similarly use [self unschedule:@selector(tick2:)] inside tick2: when you want it to stop repeating.
adam
[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