문제

CoCOS2D를 사용하여 2D iPhone 게임을 개발하고 있습니다. 카운트 다운 타이머가 필요합니다. cocos2d에서 카운트 다운 타이머를 어떻게 만들 수 있습니까?

도움이 되었습니까?

해결책

톰을 쫓아 내기에 충분한 담당자는 아니지만 그는 절대적으로 옳습니다. 이 질문의 맥락에서 Nstimer는 잘못된 해결책입니다. CoCOS2D 프레임 워크는 일시 정지/이력서와 같은 다른 게임 기능과 통합되는 스케줄러를 제공합니다 (대부분 NSTIMER를 후드에서 사용 함).

위의 링크에서 예 :

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

다른 팁

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

  • 노력하다 아니다 Cocoa의 Nstimer를 사용합니다. 대신 CoCOS2D의 자체 스케줄러를 사용하십시오.
  • Cocos2d 스케줄러를 사용하는 경우 다음과 같습니다.
    • 자동 일시 정지/이력서.
    • 레이어 (Scene, Sprite, Cocosnode)가 스테이지에 들어가면 타이머가 자동으로 활성화되고 스테이지가 떠날 때 자동 비활성화됩니다.
    • 대상/선택기는 델타 시간으로 호출됩니다 ...

Cocos 2D에는 타이머에 대한 기본 업데이트 섹션이 있습니다.

이 시도:

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

"일정"메소드 대신 Nstimer를 사용하려는 사람들의 경우 다음과 같은 클래스를 만들 수 있습니다.

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

Nstimer를 보면 필요한 타이머 기능을 제공 할 수 있습니다.

Nstimer 클래스 참조

-(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
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top