Pirates
Pirates

Reputation: 107

What is the best way to create a countdown timer in Cocos2d-x?

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

Answers (1)

ThunderStruct
ThunderStruct

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:

  1. 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)

  2. 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
    
  3. 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

Related Questions