Callback in cocos2d-x
09 Feb 2014Callback, the ability to declare a piece of code to be run at some time later, is essential in game development. cocos2d provides an easy-to-use mechanism to run callback via CCNode.runAction()
through CCCallFunc family. We can extend its mechanism to run callback any time we want, regardless of CCNode or CCCallFunc.
Callback in CCNode.runAction()
cocos2d-x (and cocos2d-iphone) provides a bunch of CCAction subclasses which allow you to do callback in CCNode.runAction()
. They are:
CCCallFunc
: calls a function with no argumentsCCCallFuncN
: calls a function with the node as the first argument.N
stands for nodeCCCallFuncND
: calls a function with the node as the first argument and the 2nd argument is params.ND
means: Node and Data. Data isvoid *
, so it could be anything.CCCallFuncO
: calls a function with anCCObject *
as the first argument.O
stands for object.
Some examples with detailed explanation:
Callback outside of CCNode.runAction()
There’re times when you need to do callback outside of runAction()
, for example: callback on network response, callback when a long calculation finishes…
In these cases, you need to store 2 things:
- Pointer to the object being called function on, or target object
- Selector to the function being called
And when you need to run callback:
You can change SEL_CallFunc
to SEL_CallFuncN
, SEL_CallFuncND
or SEL_CallFuncO
to pass some parameters along.
Comments
comments powered by Disqus