Time for action – using the event dispatcher
If we want the Platform
sprite to listen to the special notification NOTIFICATION_GRAVITY_SWITCH
, all we need to do is add Platform
as an observer.
- Inside the
Platform
class, in its constructor, you will find these lines:auto onGravityChanged = [=] (EventCustom * event) { if (this->isVisible()) { switchTexture(); } }; Director::getInstance()->getEventDispatcher()- addEventListenerWithSceneGraphPriority(EventListenerCustom::create (GameLayer::NOTIFICATION_GRAVITY_SWITCH, onGravityChanged), this);
And yes, it is one line of code! It is best to create a macro for both the dispatcher and the add listener code; so, something like this:
#define EVENT_DISPATCHER Director::getInstance()- >getEventDispatcher() #define ADD_NOTIFICATION( __target__, __notification__, __handler__) EVENT_DISPATCHER- addEventListenerWithSceneGraphPriority(EventListenerCustom::create (__notification__, __handler__), __target__);
This...