【问题标题】:How to Show a Countdown Timer in Cocos2d?如何在 Cocos2d 中显示倒数计时器?
【发布时间】:2015-10-22 18:30:40
【问题描述】:

我正在使用 c++ 在 Cocos2d-X v3 中做一个平台游戏。

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

这样做的最佳方式是什么? 我对 Cocos 和游戏开发还很陌生

【问题讨论】:

  • 参考#include 头文件类和函数。这些适用于像您这样与时间相关的活动

标签: c++ cocos2d-x cocos2d-x-3.0


【解决方案1】:

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

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

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
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      就是这样!
      有关 ProgressTimer 的更多信息,您可以找到 here。该链接是 Cocos2d-x v.2.x 的示例,但带有示例和图像。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-01
        • 1970-01-01
        • 2017-04-21
        • 1970-01-01
        • 2011-07-29
        • 1970-01-01
        相关资源
        最近更新 更多