Reputation: 107
I am making a game in cocos2dx but I don't know how to create a countdown timer so that the player only has a certain amount of time to complete the level before time runs out.
Upvotes: 1
Views: 369
Reputation: 1504
You can use the schedule
method to call a function after a certain amount of time and update your timer's label accordingly.
Check this out:
Create a private int
member called countdown
for instance and initialize it with the number of seconds you want to countdown from. Also, declare the timer's Label
(let's call it lbl
)
in your scene's init
method, schedule an updater and initialize the label like this
this->lbl = Label::createWithTTF(std::to_string(this->countdown), "fonts/Marker Felt.ttf", charSize / 15); // make sure you #include <string>
lbl->setPosition(Vec2(0,0)); // set the position to wherever you like
this->schedule(schedule_selector(MySceneClass::updateTimer), 1.0f); // calls updateTimer once every second
declare and implement the updateTimer
to look something like this:
void MySceneClass::updateTimer(float dt)
{
if (!countdown)
return; // when countdown reaches 0, stop updating to avoid negative values
lbl->setString(std::to_string(--countdown));
}
Upvotes: 1