如何在Cocos2d中显示倒计时计时器
How to Show a Countdown Timer in Cocos2d?
我在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的一个示例。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 字符串-C++后显示的随机字符
- 继承期间显示未知行为的子类
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- 程序崩溃并显示"std::out_of_range"错误
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 从数据库实时显示QT c++中的数据
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 显示错误输出的简单数组排序程序
- Qt自定义QPush按钮未显示在布局上
- C++射线示踪剂ppm表示没有足够的数据来显示图像
- 显示基于用户输入的整数的字符
- 使用QTreeView,如何通过调用函数只突出显示特定的行/列
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 示例外壳应用程序显示的 V8 "segmentation fault (core dumped)"错误
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 密码登录程序将永远循环并显示不正确的结果
- 如何在Cocos2d中显示倒计时计时器