In Objective C calling a selector after a given delay is a piece of cake as this is built in
NSObject. Everyone who has touched the iPhone SDK has one time or another come across the following code:
[self performSelector:@selector(doSomething) withObject:nil afterDelay:0.5f];
If you haven’t got a clue what that does, it calls the
doSomething method on the current object after a 0.5 second delay. Useful when you want to perform an action after the user does something or to hide a notification after a while.
It’s not that particularly complicated to do the same thing in C++, but you need to make use of some of Cocos2D-x features such as
First, let’s look at the code:
// set up the time delay
CCDelayTime *delayAction = CCDelayTime::actionWithDuration(0.5f);
// perform the selector call
CCCallFunc *callSelectorAction = CCCallFunc::actionWithTarget(this,
// run the action
First, you need to set up the time delay using a
CCDelayTime action. Simple enough, you send the duration of the intended delay as an argument to the method.
Then, you need to set up the selector call action. The first argument you are going to send is the object to perform the action on, the second one is a pointer to the function from that object. After the time delay action expires, the
doSomething method will be called on the object represented by
this. In my case,
this is the scene layer.
If you are wondering,
callfunc_selector is a macro that simply casts the pointer of the argument it receives to a
SEL_CallFunc. This is what this baby looks like:
#define callfunc_selector(_SELECTOR) (SEL_CallFunc)(&_SELECTOR)
Finally, we call
runAction on the current scene. The
runAction method takes as a parameter a
CCSequence object. This CCSequence object allows you to chain together multiple sequential actions.
You must separate your action by a comma, and ALWAYS close the list of actions with a
NULL. Failure to do so will crash your app as there is no way for CCSequence to know when to stop executing actions. This is especially true for Android, and especially weird on iOS where it doesn’t crash, but what you need to keep in mind is to always close an enumeration of actions with a
Hope this helps you Cocos2D-x noobs 😛