[Switch] event distribution mechanism

Source: Internet
Author: User
Event distribution mechanism

New event distribution mechanism:During event processing in version 2.x, events to be triggered are handed over to the proxy (delegate) for processing, events are received by ontouchbegan in the proxy, and finally the event response is completed. In the new event distribution mechanism, you only need to create an event listener to implement various trigger logic and then add it to the event distributor._eventDispatcherAll Event Listeners can be centrally managed by this distributor to Complete Event Response.

Event Listeners include the following types:

  • Eventlistenertouch)
  • Eventlistenerkeyboard)
  • Eventlistenermouse)
  • Custom Event (eventlistenercustom)
  • Eventlisteneracceleration)

_eventDispatcherConsists of three parts:

  • Eventdispatcher
  • Event types such as eventtouch and eventkeyboard
  • Event Listeners such as eventlistenertouch and eventlistenerkeyboard

The listener implements various trigger logics. When appropriate, the event distributor distributes event types and calls corresponding types of listeners.

User input event touch event

When processing a touch event, you can override three methods.onTouchBegan,onTouchMovedAndonTouchEndedYou can also use lambda expressions to complete the response logic.

In 2.xAppController.mmInapplication didFinishLaunchingWithOptions:launchOptionsAdd[__glView setMultipleTouchEnabled: YES]In addition, you need to reload 5 corresponding functions:

  • Virtual void registerwithtouchdispatcher (void );
  • Virtual void cctouchesbegan (cocos2d: ccset * ptouches, cocos2d: ccevent * pevent );
  • Virtual void cctouchesmoved (cocos2d: ccset * ptouches, cocos2d: ccevent * pevent );
  • Virtual void cctouchesended (cocos2d: ccset * ptouches, cocos2d: ccevent * pevent );
  • Virtual void cctouchescancelled (cocos2d: ccset * ptouches, cocos2d: ccevent * pevent );

In 3.0, you only need to create a multi-touch event listener and add it to the event distributor.

The following code adds three buttons to an interface, which are blocked by each other and trigger a touch event:

// Create button sprite1 = sprite: Create ("images/cyansquare.png"); sprite1-> setposition (origin + point (size. width/2, size. height/2) + point (-80, 80); addchild (sprite1, 10); // sprite2... // sprite3...

After creating the button genie, create a single point of touch event listener and complete corresponding logic processing.

// Create a single-touch auto listener1 = eventlistenertouchonebyone with the event listener type onebyone: Create (); // you can specify whether the event is swallowed up, when the ontouchbegan method returns true, the listener1-> setswallowtouches (true) is swallowed; // use Lambda to implement the ontouchbegan Event Callback Function listener1-> ontouchbegan = [] (touch * touch, * event) {// obtain the target auto target = static_cast <sprite *> (Event-> getcurrenttarget () bound to the event ()); // obtain the coordinates of the Point locationinnode = target-> converttonodespace (touch-> getlocation (); Size S = target-> getcontentsize (); rect = rect (0, 0, S. width, S. height); // click the range to determine if (rect. containspoint (locationinnode) {log ("Sprite began... X = % F, y = % F ", locationinnode. x, locationinnode. y); Target-> setopacity (180); Return true;} return false;}; // triggers listener1-> ontouchmoved = [] (touch * touch, event * event ){...}; // click the end of the event to process listener1-> ontouchended = [=] (touch * touch, event * event ){...};

Add the event listener to the event distributor.

// Add the listener _ eventdispatcher-> addeventlistenerwithscenegraphpriority (listener1, sprite1); _ eventdispatcher-> handler (listener1-> clone (), sprite2 ); _ eventdispatcher-> addeventlistenerwithscenegraphpriority (listener1-> clone (), sprite3 );

In the above Code_eventDispatcherIs the attribute of a node. It manages the distribution of all events of the current node (scenario, layer, Genie, etc. However, it is a reference of the singleton mode value. In the node constructorDirector::getInstance()->getEventDispatcher();With this attribute, you can easily process events.

Note:When listener1 is used again, useclone()Method to create a new clone becauseaddEventListenerWithSceneGraphPriorityOraddEventListenerWithFixedPriorityMethod, a registered tag will be added to the currently used event listener, so that it cannot be added multiple times. In addition, it is very important to manually remove fixedpriority listener after it is added. scenegraphpriority listener is bound to node and will be removed from node destructor. For specific examples, refer to the tests provided by the engine.

We can remove an added listener using the following methods.

_eventDispatcher->removeEventListener(listener);

You can also remove all listeners in the current event distributor using the following method.

_eventDispatcher->removeAllEventListeners();

When usingremoveAllAll the listeners on this node will be removed. We recommend that you use the specified Delete method.removeAllThen the menu cannot respond. Because it also needs to accept touch events.

Keyboard RESPONSE event

The keyboard response event and processing touch events use the same processing method. The code below demonstrates how to handle the keyboard response event:

// Initialize and bind auto listener = eventlistenerkeyboard: Create (); listener-> onkeypressed = encrypted (keyboardtest: onkeypressed, this); listener-> onkeyreleased = cc_callback_2 (keyboardtest :: onkeyreleased, this); _ eventdispatcher-> listener (listener, this); // void keyboardtest: onkeypressed (eventkeyboard: keycode, event * event) {log ("key with keycode % d pressed", keycode);} void keyboardtest: onkeyreleased (eventkeyboard: keycode, event * event) {log ("key with keycode % d released", keycode );}
Mouse RESPONSE event

In 3.0, more Mouse capture events are distributed, which can enrich the user experience of our games on different platforms.

The following code implements the mouse response to an event:

// Create the listener _ mouselistener = eventlistenermouse: Create (); // time response logic _ mouselistener-> onmousemove = [=] (event * event) {eventmouse * E = (eventmouse *) event; string STR = "mouse down detected, key:"; STR + = tostr (e-> getmousebutton ()); //...}; _ mouselistener-> onmouseup = [=] (event * event ){...}; _ mouselistener-> onmousedown = [=] (event * event ){...}; _ mouselistener-> onmousescroll = [=] (event * event ){...}; // Add it to the event distributor _ eventdispatcher-> addeventlistenerwithscenegraphpriority (_ mouselistener, this );
Custom events

The above are built-in event types, which are automatically triggered by the system, such as touch screen and keyboard response. In addition, a custom event is provided, in short, it is not automatically triggered by the system, but human interference, as follows:

    _listener = EventListenerCustom::create("game_custom_event1", [=](EventCustom* event){        std::string str("Custom event 1 received, ");        char* buf = static_cast<char*>(event->getUserData());        str += buf;        str += " times";        statusLabel->setString(str.c_str());    });    _eventDispatcher->addEventListenerWithFixedPriority(_listener, 1);

The above defines a "Custom Event listener", implements the relevant logic, and adds it to the event distributor. The above Custom Event will be triggered by the following code:

    static int count = 0;    ++count;    char* buf = new char[10];    sprintf(buf, "%d", count);    EventCustom event("game_custom_event1");    event.setUserData(buf);    if(...)    {        _eventDispatcher->dispatchEvent(&event);    }    CC_SAFE_DELETE_ARRAY(buf);

Define an eventcustom and set its userdata. Manually distribute the event through _ eventdispatcher-> dispatchevent (& event); To trigger the previously implemented logic.

Accelerator event

In addition to the touch, a very important input source on a mobile device is the direction of the device. Therefore, most devices are equipped with an accelerometer to measure the gravity direction of the device when it is still or at a constant speed.

Gravity sensing is derived from a mobile accelerator. It usually supports acceleration in the X, Y, and Z directions. It is also called a three-way accelerator. In actual application, you can calculate the angle or direction of the mobile phone tilt based on the strength of the three directions.

3.0, under the new event mechanism, we need to create an accelerometer listenerEventListenerAccelerationThe static create method has an acceleration parameter. Acceleration is a class that contains three acceleration directions obtained by the accelerator. The related code is as follows:

class Acceleration{public:    double x;    double y;    double z;    double timestamp;    Acceleration(): x(0), y(0), z(0), timestamp(0) {}};

The acceleration of each direction in this class is one gravity acceleration.

Before using the accelerator event listener, you must enable this hardware device:

Device::setAccelerometerEnabled(true);

Create a listener. When creating a callback function, you can use a Lambda expression to create an anonymous function, or bind an existing function logic implementation, as shown below:

Auto listener = eventlisteneracceleration: Create ([=] (acceleration * ACC, event * event) {// logical code segment}); _ eventdispatcher-> addeventlistenerwithscenegraphpriority (listener, this );

[Switch] event distribution mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.