Calling functions with actions
You may want to call a function by triggering some actions. For example, you are controlling the sequence action, jump, and move, and you want to use a sound for the jumping action. In this case, you can call a function by triggering this jump action. In this recipe, you will learn how to call a function with actions.
How to do it...
Cocos2d-x has the CallFunc
object that allows you to create a function and pass it to be run in your Sequence
. This allows you to add your own functionality to your Sequence
action.
auto move = MoveBy::create(2.0f, Vec2(100, 0)); auto rotate = RotateBy::create(2.0f, 360.0f); auto func = CallFunc::create([](){ CCLOG("finished actions"); }); auto action = Sequence::create(move, rotate, func, nullptr); sprite->runAction(action);
The preceding command will execute the following actions sequentially:
Move a sprite 100px to the right over two seconds
Rotate a sprite clockwise by 360 degrees over two seconds
Execute CCLOG