Cocos Basic Tutorials (11) Event distribution mechanism

Source: Internet
Author: User
Tags event listener

cocos3.0 Event Distribution mechanism:

    • Create an event listener-used to implement various post-trigger logic.
    • Event listeners are added to the event dispatcher _eventDispatcher , and all event listeners have this dispatcher unified management.

There are several event listeners:

    • Touch Events (Eventlistenertouch)
    • Keyboard response Events (Eventlistenerkeyboard)
    • Mouse Response Events (Eventlistenermouse)
    • Custom Events (Eventlistenercustom)
    • Speeding up Logging events (eventlisteneracceleration)

_eventDispatcherWork consists of three parts:

    • Event Dispatcher Eventdispatcher
    • Event Type Eventtouch, Eventkeyboard, etc.
    • Event Listener Eventlistenertouch, Eventlistenerkeyboard, etc.
Touch events

When dealing with touch events, you can override three methods onTouchBegan , onTouchMoved and you onTouchEnded can also complete the response logic directly through a lambda expression. The touch-type touch events are divided into Eventlistenertouchonebyone and eventlistenertouchallatonce. Eventlistenertouchonebyone represents a single touch, while Eventlistenertouchallatonce represents a multi-touch.

    1. Just create a multi-touch event listener.
    2. You can add it to the event dispatcher.
 //Create a single touch with event listener type OneByOneAuto Listener1 =eventlistenertouchonebyone::create (); //sets whether the engulfing event is swallowed when the Ontouchbegan method returns TrueListener1->setswallowtouches (true); //implementing the Ontouchbegan event callback function using lambdaListener1->ontouchbegan = [] (touch* Touch, event*Event){        //gets the target that the event is bound toAuto target = static_cast<sprite*> (Event-getcurrenttarget ()); //gets the position coordinates of the relative button where the current click is located .Point Locationinnode = Target->converttonodespace (touch->getLocation ()); Size s= target->getcontentsize (); Rect rect= Rect (0,0, S.width, s.height); //Click Range Judgment Detection        if(Rect.containspoint (locationinnode)) {log ("Sprite began ... x =%f, y =%f", locationinnode.x, locationinnode.y); Target->setopacity ( the); return true; }        return false;    }; //trigger when Touch moveslistener1->ontouchmoved = [] (touch* Touch, event*Event){...}; //Click event End Processinglistener1->ontouchended = [=] (touch* Touch, event*Event){...};

Finally, you need to add the event listener to the event dispatcher

    // Add Listener    _eventdispatcher->addeventlistenerwithscenegraphpriority (Listener1, sprite1);    _eventdispatcher->addeventlistenerwithscenegraphpriority (listener1->clone (), sprite2);    _eventdispatcher->addeventlistenerwithscenegraphpriority (Listener1->clone (), sprite3);

The above code _eventDispatcher is the attribute of node, which manages the distribution of all events of the current node (scene, layer, Sprite, etc.). But it itself is a reference to a singleton pattern value, which, in node's constructor, Director::getInstance()->getEventDispatcher(); can be easily handled by obtaining this property.

注意:When you use Listener1 again, you need to use a clone() method to create a new clone, because addEventListenerWithSceneGraphPriority addEventListenerWithFixedPriority when you use the or method, a registered token is added to the currently used event listener, which makes it not able to be added more than once. In addition, it is very important that fixedpriority listener need to be removed after adding it, and scenegraphpriority listener is bound to node and will be deleted in the destructor of node. The specific example usage can refer to the tests that the engine comes with.

We can remove a listener that has been added in the following ways.

_eventDispatcher->removeEventListener(listener);

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

_eventDispatcher->removeAllEventListeners();

When used removeAll , all of this node's listener will be removed, the recommended way to specify the deletion. The removeAll menu will not respond after that. Because it also needs to accept touch events.

Keyboard Response Events

The keyboard responds to events and handles touch events using the same processing, and the code demonstrates how to handle keyboard response events:

    //Initialize and bindAuto Listener =eventlistenerkeyboard::create (); Listener->onkeypressed = Cc_callback_2 (keyboardtest::onkeypressed, This); Listener->onkeyreleased = Cc_callback_2 (keyboardtest::onkeyreleased, This); _eventdispatcher->addeventlistenerwithscenegraphpriority (Listener, This); //keying response function prototype    voidKeyboardtest::onkeypressed (Eventkeyboard::keycode keycode, event*Event) {log ("Key with keycode%d pressed", KeyCode); }    voidKeyboardtest::onkeyreleased (Eventkeyboard::keycode keycode, event*Event) {log ("Key with KeyCode%d released", KeyCode); }
Mouse Response Events

In 3.0 more mouse capture event distribution, which can be on different platforms, enrich the user experience of our game.

The following code implements the steps for implementing the mouse response event:

    //Creating listeners_mouselistener =eventlistenermouse::create (); //Time Response Logic_mouselistener->onmousemove = [=] (Event *event) {eventmouse* e = (eventmouse*)Event; stringstr ="Mouse down detected, Key:"; STR+ = Tostr (e->Getmousebutton ()); // ...}; _mouselistener->onmouseup = [=] (Event *Event){...}; _mouselistener->onmousedown = [=] (Event *Event){...}; _mouselistener->onmousescroll = [=] (Event *Event){...}; //Add to Event dispatcher_eventdispatcher->addeventlistenerwithscenegraphpriority (_mouselistener, This);
Custom events

The above is the system comes with the type of event, the event is automatically triggered by the system, such as touch screen, keyboard response, in addition, also provides a custom event, in short, it is not triggered by the system automatically, but the human intervention, as follows:

_listener = Eventlistenercustom::create ("Game_custom_event1", [=] (eventcustom*Event) {std::stringStr"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" that implements the relevant logic and is added to the event dispatcher. The above custom event will be triggered by the following code:

    Static intCount =0; ++count; Char* BUF =New Char[Ten]; sprintf (BUF,"%d", Count); EventcustomEvent("Game_custom_event1"); Event. Setuserdata (BUF); if(...) {_eventdispatcher->dispatchevent (&Event); } cc_safe_delete_array (BUF);

Define a eventcustom, and set its UserData data, manually through the _eventdispatcher->dispatchevent (&event); This event is distributed to trigger the previously implemented logic.

Accelerometer Events

In addition to touch, a very important input source on a mobile device is the direction of the device, so most devices are equipped with accelerometers to measure the gravity direction of the device when it is stationary or uniform motion.

Gravity sensing accelerometers from mobile devices, typically support acceleration sensing in X, Y and z three directions, so it's called a three-way accelerometer. In practical applications, the angle or direction of the phone tilt can be calculated based on the force size in 3 directions.

3.0, under the new event mechanism, we need to be EventListenerAcceleration aware of a acceleration parameter in the static create method by creating an accelerometer listener. Acceleration is a class that contains the acceleration in 3 directions obtained by the accelerometer, with the relevant code as follows:

class acceleration{public:    double  x;     Double y;     Double Z;     Double timestamp;    Acceleration (): X (0), y (0), Z (0), timestamp (0) {}};

The acceleration size for each direction in the class is one of the gravitational acceleration size.

Before using the Accelerometer event listener, you need to enable this hardware device:

Device::setAccelerometerEnabled(true);

Then create the corresponding listener, you can create an anonymous function using a lambda expression when you create the callback function, or you can bind an existing function logic implementation, as follows:

    Event ) {        // Logical Code Snippet     });    _eventdispatcherthis);

Cocos Basic Tutorials (11) 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.