如何为cocos2d创建倒计时器?

时间:2021-08-10 10:05:03

I am developing a 2D iPhone game by using cocos2d. I need a countdown timer. How can I create a count down timer in cocos2d?

我正在使用cocos2d开发2D iPhone游戏。我需要一个倒数计时器。如何在cocos2d中创建倒计时器?

6 个解决方案

#1


49  

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).

没有足够的代表来支持汤姆,但他是绝对正确的。在这个问题的背景下,NSTimer是错误的解决方案。 Cocos2d框架提供了一个调度程序,可以与其他游戏功能集成,例如Pause / Resume(最常见的是使用NSTimer)。

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
}

#2


16  

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

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

  • Try NOT to use Cocoa’s NSTimer. Instead use cocos2d’s own scheduler.
  • 尽量不要使用Cocoa的NSTimer。而是使用cocos2d自己的调度程序。
  • If you use cocos2d scheduler, you will have:
    • automatic pause/resume.
    • 自动暂停/恢复。
    • when the Layer (Scene, Sprite, CocosNode) enters the stage the timer will be automatically activated, and when it leaves the stage it will be automatically deactivated.
    • 当Layer(Scene,Sprite,CocosNode)进入舞台时,计时器将自动激活,当它离开舞台时,它将自动停用。
    • Your target/selector will be called with a delta time...
    • 您的目标/选择器将使用增量时间调用...
  • 如果您使用cocos2d调度程序,您将拥有:自动暂停/恢复。当Layer(Scene,Sprite,CocosNode)进入舞台时,计时器将自动激活,当它离开舞台时,它将自动停用。您的目标/选择器将使用增量时间调用...

#3


4  

In cocos 2d there is default update section for timer.

在cocos 2d中有定时器的默认更新部分。

Try this:

尝试这个:

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

#4


3  

For those that want to use NSTimer instead of the "schedule" method, you can create a class such as the following:

对于那些想要使用NSTimer而不是“schedule”方法的人,可以创建一个类,如下所示:

ZIMCountdownTicker.h

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

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

#5


-5  

Look at NSTimer, it can most likely provide any needed timer functionality.

看看NSTimer,它很可能提供任何所需的计时器功能。

NSTimer class reference

NSTimer类参考

#6


-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
}

#1


49  

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).

没有足够的代表来支持汤姆,但他是绝对正确的。在这个问题的背景下,NSTimer是错误的解决方案。 Cocos2d框架提供了一个调度程序,可以与其他游戏功能集成,例如Pause / Resume(最常见的是使用NSTimer)。

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
}

#2


16  

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

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

  • Try NOT to use Cocoa’s NSTimer. Instead use cocos2d’s own scheduler.
  • 尽量不要使用Cocoa的NSTimer。而是使用cocos2d自己的调度程序。
  • If you use cocos2d scheduler, you will have:
    • automatic pause/resume.
    • 自动暂停/恢复。
    • when the Layer (Scene, Sprite, CocosNode) enters the stage the timer will be automatically activated, and when it leaves the stage it will be automatically deactivated.
    • 当Layer(Scene,Sprite,CocosNode)进入舞台时,计时器将自动激活,当它离开舞台时,它将自动停用。
    • Your target/selector will be called with a delta time...
    • 您的目标/选择器将使用增量时间调用...
  • 如果您使用cocos2d调度程序,您将拥有:自动暂停/恢复。当Layer(Scene,Sprite,CocosNode)进入舞台时,计时器将自动激活,当它离开舞台时,它将自动停用。您的目标/选择器将使用增量时间调用...

#3


4  

In cocos 2d there is default update section for timer.

在cocos 2d中有定时器的默认更新部分。

Try this:

尝试这个:

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

#4


3  

For those that want to use NSTimer instead of the "schedule" method, you can create a class such as the following:

对于那些想要使用NSTimer而不是“schedule”方法的人,可以创建一个类,如下所示:

ZIMCountdownTicker.h

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

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

#5


-5  

Look at NSTimer, it can most likely provide any needed timer functionality.

看看NSTimer,它很可能提供任何所需的计时器功能。

NSTimer class reference

NSTimer类参考

#6


-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
}