Book Image

Cocos2d-x by Example: Beginner's Guide

By : Roger Engelbert
Book Image

Cocos2d-x by Example: Beginner's Guide

By: Roger Engelbert

Overview of this book

Table of Contents (19 chapters)
Cocos2d-x by Example Beginner's Guide Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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.

  1. 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 way the...