Book Image

Cocos2d-x by Example: Beginner's Guide

By : Roger Engelbert
Book Image

Cocos2d-x by Example: Beginner's Guide

By: Roger Engelbert

Overview of this book

Table of Contents (19 chapters)
Cocos2d-x by Example Beginner's Guide Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – creating a timer


We create timers in pretty much the same way we create our main loop.

  1. First, we add a second scheduled event by adding this line to our GameLayer constructor:

    this->schedule(CC_SCHEDULE_SELECTOR(GameLayer::ticktock), 1.5f);
  2. With this, we create a separate timer that will run the ticktock method every 1.5 seconds (I decided in the end that 1.5 seconds looked better).

  3. The method keeps updating the value of the _time property and displaying it in the _timer label.

    void GameLayer::ticktock(float dt) {
        if (_gameState == kGamePlay) {
            _time++;
            _timer->setString(std::to_string(_time));
        }
    }

What just happened?

We added a timer to our game by scheduling a second update—specifying the time interval we wanted—using the schedule method.

If you wish to remove a timer, all you need to do is call the unschedule(SEL_SCHEDULE selector) method of nodes anywhere in your class.

Now, let's take our Box2D game to Android.