2009-01-15 6 views

Répondre

49

Pas assez de représentant Upvote Tom, mais il est tout à fait raison. Dans le contexte de cette question, NSTimer est la solution WRONG. Le framework Cocos2d fournit un planificateur qui s'intègre à d'autres fonctionnalités de jeu telles que Pause/Resume (et utilise probablement NSTimer sous le capot).

Exemple à partir du lien ci-dessus:

-(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 
} 
+2

et de même utiliser [self unschedule: @selector (tick2 :)] inside tick2: quand vous voulez qu'il arrête de répéter. – adam

+1

[auto-planning: @selector (cocher :)]; quand j'essaie de le faire dans mon code ... mon application ne trouve pas d'horaire ... c'est fonction de quelle classe ...? –

+0

@mihir CCLayer Je crois, généralement en superclasse –

-5

Regardez NSTimer, il peut très probablement fournir n'importe quelle fonctionnalité de temporisateur nécessaire.

NSTimer class reference

-13
-(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 
{ 
    //some function here 
} 

-(void) tick2: (ccTime) dt 
{ 
    //some function here 
} 
+0

Merci pour votre réponse. son fonctionnement .... – Nasir

+5

C'est la mauvaise façon de le faire en utilisant cocos2d, vous devez faire ce que les autres ont dit et utiliser les trucs [self schedule:]. Les principales raisons sont que l'utilisation de NSTimer ne supporte pas les commandes de pause, de démarrage et d'arrêt de cocos2d. – Solmead

+0

A redire: NE PAS UTILISER NSTimer! C'est faux. – Sneakyness

16

http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:best_practices

  • Essayez PAS à utiliser NSTimer de cacao. Utilisez plutôt le propre planificateur de cocos2d.
  • Si vous utilisez planificateur cocos2d, vous aurez:
    • pause automatique/CV.
    • Lorsque le calque (Scene, Sprite, CocosNode) entre dans la scène, la minuterie sera automatiquement activée, et quand elle quitte la scène, elle sera automatiquement désactivée.
    • Votre cible/sélecteur sera appelé avec un temps delta ...
4

Dans 2d cocos il y a la section de mise à jour par défaut pour la minuterie.

Essayez ceci:

[self schedule:@selector(update:)]; 
- (void)update:(ccTime)dt { 
} 
3

Pour ceux qui veulent utiliser NSTimer au lieu de la méthode "calendrier", vous pouvez créer une classe comme les suivants:

ZIMCountdownTicker.h

#import <Foundation/Foundation.h> 

extern NSString * const ZIMCountdownTickerTickAction; 
extern NSString * const ZIMCountdownTickerResetAction; 

@protocol ZIMCountdownTickerProtocol; 

/*! 
@class    ZIMCountdownTicker 
@discussion  This class creates a countdown ticker. 
@updated   2011-03-05 
*/ 
@interface ZIMCountdownTicker : NSObject { 

    @private 
     NSTimer *_timer; 
     id<ZIMCountdownTickerProtocol> _delegate; 
     NSTimeInterval _interval; 
     double _period; 
     double _value; 

} 

/*! 
@method    initWithDelegate:withTimeInterval:forTimePeriod: 
@discussion   This method instantiate an instance of this class with the specified parameters. 
@param delegate  A reference to a class that has implemented ZIMCountdownTickerProtocol. 
@param interval  The time interval in seconds to be used when running the countdown ticker. 
@param period   The time period in seconds for which countdown ticker will run. 
@updated    2011-03-05 
*/ 
- (id) initWithDelegate: (id<ZIMCountdownTickerProtocol>)delegate withTimeInterval: (NSTimeInterval)interval forTimePeriod: (double)period; 
/*! 
@method    start 
@discussion   This method will start the countdown ticker. 
@updated    2011-03-05 
*/ 
- (void) start; 
/*! 
@method    stop 
@discussion   This method will stop the countdown ticker. 
@updated    2011-03-05 
*/ 
- (void) stop; 
/*! 
@method    reset 
@discussion   This method will reset the countdown ticker. 
@updated    2011-03-06 
*/ 
- (void) reset; 
/*! 
@method    value 
@discussion   This method will return the countdown ticker's current value; however, using this method will cause 
        the ticker to stop. 
@return    The countdown ticker's current value. 
@updated    2011-03-05 
*/ 
- (double) value; 

@end 

@protocol ZIMCountdownTickerProtocol <NSObject> 

@optional 
/*! 
@method    countdownTicker:didUpdateValue:withAction: 
@discussion   This method will notify the delegate with the current value. 
@param ticker   A reference to tiggering ticker. 
@param value   The current value. 
@param action   The action that tiggered this method. 
@updated    2011-03-05 
*/ 
- (void) countdownTicker: (ZIMCountdownTicker *)ticker didUpdateValue: (double)value withAction: (NSString *)action; 
/*! 
@method    countdownTickerDidFinish: 
@discussion   This method will notify the delegate that the countdown ticker finished. 
@param ticker   A reference to tiggering ticker. 
@updated    2011-03-05 
*/ 
- (void) countdownTickerDidFinish: (ZIMCountdownTicker *)ticker; 

@end 

ZIMCountdownTicker.m

// Ziminji Classes 
#import "ZIMCountdownTicker.h" 

NSString * const ZIMCountdownTickerTickAction = @"ticker.tick"; 
NSString * const ZIMCountdownTickerResetAction = @"ticker.reset"; 

/*! 
@category   ZIMCountdownTicker (Private) 
@discussion  This category defines the prototypes for this class's private methods. 
@updated   2011-03-05 
*/ 
@interface ZIMCountdownTicker (Private) 
    /*! 
    @method   countdown: 
    @discussion  This method is called by the timer to decrement the counter's value and will send 
        the delegate the updated value. 
    @param timer  The timer currently in use. 
@updated   2011-03-06 
    */ 
    - (void) countdown: (NSTimer *)timer; 
@end 

@implementation ZIMCountdownTicker 

- (id) initWithDelegate: (id<ZIMCountdownTickerProtocol>)delegate withTimeInterval (NSTimeInterval)interval forTimePeriod: (double)period { 
    if (self = [super init]) { 
     _delegate = delegate; 
     _interval = interval; 
     _period = period; 
     _value = period; 
     _timer = nil; 
    } 
    return self; 
} 

- (void) start { 
    if (_timer == nil) { 
     _timer = [NSTimer scheduledTimerWithTimeInterval: _interval target: self selector: @selector(countdown:) userInfo: nil repeats: YES]; 
    } 
} 

- (void) stop { 
    if (_timer != nil) { 
     [_timer invalidate]; 
     _timer = nil; 
    } 
} 

- (void) reset { 
    [self stop]; 
    _value = _period; 
    if ((_delegate != nil) && [_delegate respondsToSelector: @selector(countdownTicker:didUpdateValue:withAction:)]) { 
     [_delegate countdownTicker: self didUpdateValue: _value withAction: ZIMCountdownTickerResetAction]; 
    } 
} 

- (double) value { 
    [self stop]; 
    return _value; 
} 

- (void) countdown: (NSTimer *)timer { 
    _value -= 1; 
    if ((_delegate != nil) && [_delegate respondsToSelector: @selector(countdownTicker:didUpdateValue:withAction:)]) { 
     [_delegate countdownTicker: self didUpdateValue: _value withAction: ZIMCountdownTickerTickAction]; 
    } 
    if (_value <= 0) { 
     [self stop]; 
     if ((_delegate != nil) && [_delegate respondsToSelector: @selector(countdownTickerDidFinish:)]) { 
      [_delegate countdownTickerDidFinish: self]; 
     } 
    } 
} 

- (void) dealloc { 
    if (_delegate != nil) { 
     [_delegate release]; 
    } 
    if (_timer != nil) { 
     [_timer invalidate]; 
    } 
    [super dealloc]; 
} 

@end 
Questions connexes