Performing a selector after a delay in Cocos2D-x

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.app

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 CCSequence, CCDelayTime and CCCallFunc.ide

First, let’s look at the code:ui

  1. // set up the time delay
  2. CCDelayTime *delayAction = CCDelayTime::actionWithDuration(0.5f);
  3. // perform the selector call
  4. CCCallFunc *callSelectorAction = CCCallFunc::actionWithTarget(this,
  5. callfunc_selector(HelloWorld::doSomething));
  6. // run the action
  7. this->runAction(CCSequence::actions(delayAction,
  8. callSelectorAction,
  9. NULL));this

  10. 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.spa

    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.code

    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:orm

    #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. ip

    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 NULL.ci

    Hope this helps you Cocos2D-x noobs

http://gameit.ro/2011/09/performing-a-selector-after-a-delay-in-cocos2d-x/get

相關文章
相關標籤/搜索