如何在Cocos2d中显示倒计时计时器

How to Show a Countdown Timer in Cocos2d?

本文关键字:显示 倒计时 计时器 Cocos2d      更新时间:2023-10-16

我在Cocos2d-X v3中使用c++制作平台游戏。

我想在每个关卡设置一个倒计时计时器,所以当倒计时达到00:00时游戏结束。并将其显示在屏幕的右上角,以便玩家能够意识到这一点。

这样做的最好方法是什么?

如果你只想在标签中显示时间,还有另一种解决方案:

1)创建一个float变量,它将存储剩余时间。同时声明更新函数和时间标签:

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

2)在init函数中初始化它,并调度更新:

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
}

第三种选择是使用调度器。

//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");

最简单的方法是使用名为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));
}

在你的updateTime方法中:

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

就是这样!
你可以在这里找到更多关于progrestimer的信息。该链接是Cocos2d-x v.2的一个示例。