Reputation: 191
I'm doing a platformer game in Cocos2d-X v3 using c++.
I want to set a countdown timer in each level, so when the countdown reaches 00:00 it's game over. And show it in the top right corner of the screen, so the player could get aware of this.
What's the best way of doing so? I'm fairly new to Cocos and game development
Upvotes: 1
Views: 3489
Reputation: 70
A third option is using the scheduler.
//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");
Upvotes: 3
Reputation: 7531
There' also another solution if you just want to display time in label:
1) create a float variable, which will store remaining time. Also declare update function and time label:
float time;
virtual void update(float delta);
ui::Label txtTime;
2) initialize it in init function and schedule update:
time = 90.0f;
scheduleUpdate();
//create txtTime here or load it from CSLoader (Cocos studio)
3) update your time:
void update(float delta){
time -= delta;
if(time <= 0){
time = 0;
//GAME OVER
}
//update txtTime here
}
Upvotes: 3
Reputation: 409
The simplest way is use Cococs2d-x class named ProgressTimer.
First you need a sprite of your timer and define two float variables: maximumTimePerLevel, currentTime:
float maximumTimePerLevel = ... // your time
float currentTime = maximumTimePerLevel
auto sprTimer = Sprite::create("timer.png");
Then you init your timer:
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));
}
In your's updateTime method:
void Timer::updateTime(float dt)
{
currentTime -= dt;
timeBar->setPercentage(100 * currentTime / maximumTimePerLevel);
if (currentTime <= 0 && !isGameOver)
{
isGameOver = true;
// all Game Over actions
}
}
That's it!
More about the ProgressTimer you can find here. The link is an example of a Cocos2d-x v.2.x, but with examples and images.
Upvotes: 1