Cocos Creator-4. Listen, launch event, node system event, global system event

Posted by chrischen on Fri, 24 Dec 2021 02:24:59 +0100

preface

Next, learn to monitor and launch events, node system events, and so on!!
Recommended as usual Official website

1, Introduction

  1. Monitor and launch events
    Event processing is completed in the node (cc.Node). For components, you can register and listen to events by accessing the node this.node. Listening events can be registered through the function this.node.on().

  2. Node system events
    System events include mouse, touch, keyboard and gravity sensing. Among them, mouse and touch events associated with node tree are directly triggered on relevant nodes, so they are called node system events.

  3. Global system events
    Global system events refer to various global events that are not related to the node tree and are controlled by CC Systemevent for unified distribution. At present, it supports the following events: keyboard and gravity sensing

2, Monitor and launch events

There are two ways to launch events: emit and dispatchEvent. The difference between the two is that the latter can do event transmission.
Use the on method. onc listener will keep listening events after listening to the function response, unless it actively closes the event

Use the once method. Once listening will close the listening event after listening to the function response.

Use the off method to close the corresponding listening event. The parameters of the off method must correspond to the parameters of the on method one by one before closing.

Launch event: there are two ways to launch an event: emit and dispatchEvent. The difference between the two is that the latter can do event transmission.
//Listening events
this.node.on('mousedown', function ( event ) {
      console.log('Hello!');
    });
//The event listening function on can pass the third parameter target, which is used to bind the caller of the response function.
//The two calling methods have the same effect:
// Use function binding
this.node.on('mousedown', function ( event ) {
  this.enabled = false;
}.bind(this));

// Use the third parameter
this.node.on('mousedown', function (event) {
  this.enabled = false;
}, this);

//Examples of off method are as follows:
//Focus!!!!
//The parameters of the off method must correspond to the parameters of the on method one by one.
_sayHello: function () {
    console.log('Hello World');
  },

  onEnable: function () {
    this.node.on('foobar', this._sayHello, this);
  },

  onDisable: function () {
    this.node.off('foobar', this._sayHello, this);
  },




//Launch event
//When launching an event, we can pass our event parameters starting with the second parameter of the emit function. At the same time, the corresponding event parameters can be obtained in the callback registered by on.
//Key: considering the performance of the underlying event dispatch, only 5 event parameters can be passed here at most.
this.node.on('foo', function (arg1, arg2, arg3) {
      console.log(arg1, arg2, arg3);  // print 1, 2, 3
    });
let arg1 = 1, arg2 = 2, arg3 = 3;
// Only 5 event parameters can be passed at most.
this.node.emit('foo', arg1, arg2, arg3);

//Using the dispatchEvent method, the events emitted through this method will enter the event dispatch phase (in the form of bubble dispatch)
//Bubbling dispatch will continuously transfer the event from the event initiating node to its parent node until it reaches the root node or interrupt event is processed in the response function of a node stopPropagation(). 
//Add: Please note that when sending user-defined events, please do not directly create CC Event object, because it is an abstract class, please create CC Event. Eventcustom object to dispatch.
//In the component script of node c
this.node.dispatchEvent( new cc.Event.EventCustom('foobar', true) );
//It is hoped that after the event is intercepted by node b, the event will not be passed, and event.com will be called Stoppropagation() function.
this.node.on('foobar', function (event) {
  event.stopPropagation();
});


When we send the event "foobar" from node c, if nodes a and b listen to the "foobar" event, the events will be passed to nodes b and a through c in turn.

  • Event object:
    In the event listening callback, the developer will receive a CC The event object of event type, event, stopPropagation, is CC The standard API of event. Other important APIs include:

3, Node system events

Developers can either use enumeration types or directly use event names to register event listeners

// Use enumeration types to register
node.on(cc.Node.EventType.MOUSE_DOWN, function (event) {
  console.log('Mouse down');
}, this);

// Use the event name to register
node.on('mousedown', function (event) {
  console.log('Mouse down');
}, this);

1. Mouse event type and event object

The event types provided by the system are as follows:

Important APIs for mouse events (cc.Event.EventMouse) are as follows (except cc.Event standard event API):

2. Touch event type and event object


Important APIs for touch events (cc.Event.EventTouch) are as follows (except cc.Event standard event API):

It should be noted that touch events support multi touch, and each contact will send an event to the event listener.

3.cc. Other events of node


There are other settings

//To realize this requirement, you can pass in the fourth parameter true when registering touch or mouse events for node, indicating useCapture. For example:
this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStartCallback, this, true);
//When a node triggers a touchstart event, it will first send the touchstart event to all the parent node listeners registered in the capture phase, then to the node's own listeners, and finally to the event bubble phase.

Only touch or mouse events can be registered in the capture phase, and other events cannot be registered in the capture phase.
//The multi touch event is on by default. For some types of projects, in order to prevent multi-point mistouch, multi-point touch events need to be shielded, which can be closed through the following code:
cc.macro.ENABLE_MULTI_TOUCH = false;
//Pause node system events
// Pause all node system events registered on the current node. Node system events include touch and mouse events.
// If the parameter true is passed, the API will suspend node system events on this node and all its child nodes.
// example
this.node.pauseSystemEvents();
//Recovery node system events
// Recover all node system events registered on the current node. Node system events include touch and mouse events.
// If the parameter true is passed, the API will recover the node system events on this node and all its child nodes.
// example
this.node.resumeSystemEvents();

4, Global system events

Global events such as keyboards, devices, and gravity sensors are generated through the function CC systemEvent. On (type, callback, target).
The optional type s are:

  1. cc.SystemEvent.EventType.KEY_DOWN (keyboard press)
  2. cc.SystemEvent.EventType.KEY_UP (keyboard release)
  3. cc.SystemEvent.EventType.DEVICEMOTION (device gravity sensing)

1. Keyboard events

KeyCode: API

Event: API

cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);
cc.systemEvent.off(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
cc.systemEvent.off(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);

onKeyDown: function (event) {
        switch(event.keyCode) {
            case cc.macro.KEY.a:
                console.log('Press a key');
                break;
        }
    },

    onKeyUp: function (event) {
        switch(event.keyCode) {
            case cc.macro.KEY.a:
                console.log('release a key');
                break;
        }
    }

2. Equipment gravity sensing events

// Open accelerator
cc.systemEvent.setAccelerometerEnabled(true);
cc.systemEvent.on(cc.SystemEvent.EventType.DEVICEMOTION, this.onDeviceMotionEvent, this);
cc.systemEvent.off(cc.SystemEvent.EventType.DEVICEMOTION, this.onDeviceMotionEvent, this);
onDeviceMotionEvent (event) {
        cc.log(event.acc.x + "   " + event.acc.y);
    },

summary

There are about script events. Let's add them in the future!

Topics: Javascript TypeScript cocos2d