Cocos2D-x Tutorials Part 5: Schedule update and Actions Pause and Resume
In the previous tutorial we saw how to create actions and run them in single order or sequentially. In this tutorial we will see how to schedule a function that will be called on every frame and how can we pause and resume the whole scene or specific schedule/action.
Before we proceed lets learn about one important Cocos2D-x function and that is CCLOG.
CCLOG can print your data in console. Its like printf()/ function in C.
if you don’t know about .VA_ARGS. this is the right time to learn about it and see its real implementation, but that’s not needed for now.
CCLOG("window width is %.1f and height is %.1f", Director::getInstance()->getWinSize().width, Director::getInstance()->getWinSize().height);
Now what is a scheduler ?? A scheduler is a function that will keep executing until we want him to stop. We can also resume it if stopped.
For example we have a cloud sprite and we want it to keep moving on the background. We do that using a scheduler function.
How do we create a schedule? it’s really simple.
this->schedule(schedule_sclector(scheduled_function), dt);
Were done ! Now after dt time interval scheduled_function will keep executing.
Can we stop and run it again ?? YES.
Can we cancel the schedule?? Of course we can.
Lets see some code:
Touch_and_Move.h
Touch_and_move.cpp
At line 25, we created the schedule. This schedule will keep calling the update function with a 0.01 sec duration.
At line 26, we see a shortcut to call the update function provided by Cocos2D-x. This scheduleUpdate function will be called at every frame and will only work if your scheduled_function is named update.
If you run the code you will see that a cloud sprite is moving continuously.
Lets see how we can pause and resume the cloud movement.
Replace the code at Touch_and_Move.cpp:
At line 2, we added a static variable of type bool to identify whether our cloud is moving or paused.
At line 32 and 33 we showed 2 different method to pause our cloud movement. Using the first method will pause all the actions and scheduler methods of our current scene and the second method will pause the scene itself.
At 38 and 39 we resume our cloud movement.
We did all this in an Touch event listener. In case you are not familiar with the new cocos2D-x event system then go to Part 3
If everything is ok, then you will be able to stop the cloud movement with a mouse click and it will be resumed with the next click.
In the next tutorial we will see how to switch between scenes in cocos2d-x.