Time for action – creating a timer
We create timers in pretty much the same way we create our main loop.
- First, we add a second scheduled event by adding this line to our
GameLayer
constructor:this->schedule(CC_SCHEDULE_SELECTOR(GameLayer::ticktock), 1.5f);
- With this, we create a separate timer that will run the
ticktock
method every1.5
seconds (I decided in the end that1.5
seconds looked better). - 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.