1
我使用Xcode 5.1和Cocos2d v3.0作爲參考。在這個練習應用程序中,我希望用戶按住屏幕。如果用戶按住一秒鐘,程序應運行「someMethod」。每秒用戶按下屏幕上的程序應該運行「someMethod」。因此,如果用戶每秒鐘在屏幕上按住總共五秒鐘,則應調用「someMethod」。如果用戶沒有按住屏幕,時間不應該運行。我希望這可以讓用戶按住每個計時器。因此,如果用戶按住一秒鐘,從屏幕上移開手指,然後再次按住計時器應重置。最後,如果用戶按住2.5秒,則「someMethod」不應該第三次被觸發。GCD Timer重複發射dispatch_suspend
我的問題是,我重複計時器沒有,如果我舉起我的手指從屏幕
這裏是我的輸出的例子停止
2014-12-03 19:47:45.987 Practice App[14739:f03] fire 2014-12-03 19:47:46.986 Practice App[14739:f03] fire //after this point in time I am not holding down on the screen 2014-12-03 19:47:47.986 Practice App[14739:f03] fire 2014-12-03 19:47:48.986 Practice App[14739:f03] fire 2014-12-03 19:47:49.986 Practice App[14739:f03] fire
@implementation GameScene
{
dispatch_source_t dispatchSource;
}
- (instancetype)init
{
if (self = [super init]){
dispatchSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
double interval = 1.0;
dispatch_time_t startTime = dispatch_time(DISPATCH_TIME_NOW, 0);
uint64_t intervalTime = (int64_t)(interval * NSEC_PER_SEC);
dispatch_source_set_timer(dispatchSource, startTime, intervalTime, 0);
dispatch_source_set_event_handler(dispatchSource, ^{
[self someMethod];
});
...
}
return self;
}
- (void)fixedUpdate:(CCTime)dt
{
if(touchState == kTouchDown){//The player is touching the screen
dispatch_resume(dispatchSource);
}
if (touchState == kTouchUp) {//The player isn't touching the screen
dispatch_suspend(dispatchSource);
}
}
- (void)someMethod{
NSLog(@"fire");
}
請勿使用GCD在Cocos2D中計時。下面解釋了這個問題,儘管這個答案是關於Sprite Kit的,它同樣適用於Cocos2D:http://stackoverflow.com/a/23978854/201863另外,如果你在cocos2d中使用動作或者調度方法,它將會是很容易創建定時器。只需查看所有代碼即可設置GCD定時器,CCNode的日程安排方法只需一行。 – LearnCocos2D 2014-12-04 08:10:41