2015-10-22 110 views
1

我在Cocos2d-X v3中用C++做了一個平臺遊戲。如何在Cocos2d中顯示倒數計時器?

我想設置每個級別的倒數計時器,所以當倒計時到達00:00時,遊戲結束。並將其顯示在屏幕的右上角,以便玩家瞭解這一點。

這樣做的最佳方式是什麼? 我對科科斯和遊戲開發相當陌生

+0

請參閱#include 頭文件類和函數。這些是爲了像你的時間相關的活動 – Anwesha

回答

2

有」此外,如果你只是想在標籤中顯示的時間另一種解決方案:

1)創建一個浮點型變量,將存儲的剩餘時間。同時聲明更新功能和時間標籤:

float time; 
virtual void update(float delta); 
ui::Label txtTime; 

2)在初始化函數和進度更新初始化:

time = 90.0f; 
scheduleUpdate(); 
//create txtTime here or load it from CSLoader (Cocos studio) 

3)更新時間:

void update(float delta){ 
    time -= delta; 
    if(time <= 0){ 
     time = 0; 
     //GAME OVER 
    } 
    //update txtTime here 
} 
1

最簡單的方法是使用名爲ProgressTimer的Cococs2d-x類。
首先,你需要你的計時器的精靈,並定義兩個浮點型變量:maximumTimePerLevel,currentTime的:

float maximumTimePerLevel = ... // your time 
float currentTime = maximumTimePerLevel 
auto sprTimer = Sprite::create("timer.png"); 

然後你初始化你的計時器:

void Timer::init() 
{ 
    auto timeBar = ProgressTimer::create(sprTimer); 
    timeBar->setType(ProgressTimer::Type::RADIAL); // or Type::BAR 
    timeBar->setMidpoint(Vec2(0.5f, 0.5f)); // set timer's center. It's important! 
    timeBar->setPercentage(100.0f); // countdown timer will be full 
    this->addChild(timeBar); 
// and then you launch countdown: 
    this->schedule(schedule_selector(Timer::updateTime)); 
} 

在你的錄入方法:

void Timer::updateTime(float dt) 
{ 
    currentTime -= dt; 
    timeBar->setPercentage(100 * currentTime/maximumTimePerLevel); 
    if (currentTime <= 0 && !isGameOver) 
    { 
     isGameOver = true; 
     // all Game Over actions 
    } 
} 

就是這樣!
有關ProgressTimer的更多信息,您可以找到here。該鏈接是Cocos2d-x v.2.x的示例,但帶有示例和圖像。

1

第三個選項是使用調度程序。

//In your .h file. 
float time; 

//In your .cpp file. 
auto callback = [this](float dt){ 
    time -= dt; 
    if(time == 0) 
    { 
     //Do your game over stuff.. 
    } 
}; 
cocos2d::schedule(callback, this, 1, 0, 0, false, "SomeKey");