2014-07-14 35 views
0

我在我的cocos2d-x遊戲(C++)ios中使用了一個計時器。我正在使用cocos2d-x 2.2版本。 我對時間的功能是在我的初始化如何使計時器保持運行,即使遊戲進入cocos2d-x C++遊戲中的背景ios

this->schedule(schedule_selector(HelloWorld::UpdateTimer), 1); 

我所定義的功能如下如下 。

void HelloWorld::UpdateTimer(float dt) 
{ 
if(seconds<=0) 
{ 
    CCLOG("clock stopped"); 
    CCString *str=CCString::createWithFormat("%d",seconds); 
    timer->setString(str->getCString()); 
    this->unschedule(schedule_selector(HelloWorld::UpdateTimer)); 

} 
else 
{ 
CCString *str=CCString::createWithFormat("%d",seconds); 
timer->setString(str->getCString()); 
seconds--; 
} 

} 

Everythings工作正常。但即使遊戲進入後臺狀態,我也有這個計時器可以繼續運行。我試過在appdelegate中評論didEnter Background的主體,但不成功。任何幫助將不勝感激 感謝

回答

0

在我的AppDelegate.cpp中,我在applicationDidEnterBackground函數中寫了下面的代碼。在這裏,當應用程序進入背景並將其存儲在CCUserdefault鍵中時,我花了幾秒鐘的時間值。當應用程序到達前臺時,我再次使用本地系統時間,並從存儲在密鑰中的時間中減去該時間。以下是我的代碼

void AppDelegate::applicationDidEnterBackground() 
{ 
    time_t rawtime; 
    struct tm * timeinfo; 
    time (&rawtime); 
    timeinfo = localtime (&rawtime); 

    CCLog("year------->%04d",timeinfo->tm_year+1900); 
    CCLog("month------->%02d",timeinfo->tm_mon+1); 
    CCLog("day------->%02d",timeinfo->tm_mday); 

    CCLog("hour------->%02d",timeinfo->tm_hour); 
    CCLog("minutes------->%02d",timeinfo->tm_min); 
    CCLog("seconds------->%02d",timeinfo->tm_sec); 

    int time_in_seconds=(timeinfo->tm_hour*60)+(timeinfo->tm_min*60)+timeinfo->tm_sec; 
    CCLOG("time in seconds is %d",time_in_seconds); 
    CCUserDefault *def=CCUserDefault::sharedUserDefault(); 
    def->setIntegerForKey("time_from_background", time_in_seconds); 

    CCDirector::sharedDirector()->stopAnimation(); 

// if you use SimpleAudioEngine, it must be pause 
// SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic(); 
} 

void AppDelegate::applicationWillEnterForeground() 
{ 

    CCUserDefault *def=CCUserDefault::sharedUserDefault(); 
    int time1=def->getIntegerForKey("time_from_background"); 
    time_t rawtime; 
    struct tm * timeinfo; 
    time(&rawtime); 
    timeinfo = localtime (&rawtime); 

    CCLog("year------->%04d",timeinfo->tm_year+1900); 
    CCLog("month------->%02d",timeinfo->tm_mon+1); 
    CCLog("day------->%02d",timeinfo->tm_mday); 

    CCLog("hour------->%02d",timeinfo->tm_hour); 
    CCLog("mintus------->%02d",timeinfo->tm_min); 
    CCLog("seconds------->%02d",timeinfo->tm_sec); 

    int time_in_seconds=(timeinfo->tm_hour*60)+(timeinfo->tm_min*60)+timeinfo->tm_sec; 
    int resume_seconds= time_in_seconds-time1; 
    CCLOG("app after seconds == %d", resume_seconds); 
    CCDirector::sharedDirector()->startAnimation(); 

// if you use SimpleAudioEngine, it must resume here 
// SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic(); 
} 

您可以看到並計算應用程序保留在後臺的時間。

0

如果應用程序在後臺獲取,除了一些特殊的後臺線程,沒有其他線程得到執行。 最好的辦法是在didEnterBackground期間將unix時間戳保存在變量中,當應用程序恢復時,獲取當前的unix時間戳並比較增量,以獲得總時間並相應地更新您的計時器。

+0

正是我做了這個,它的工作太.... –