添加全局按钮点击音效

2020-07-04  本文已影响0人  Nimanggi

Cocos Creator v2.4.0

起因:做一个小游戏需要在按钮点击的时候添加一个音效。
需求:全部的按钮在点击的时候都要播放这个音效。

  1. 启动场景中加载了一个全局控制类,可以不加,不重要。
onLoad() {
        const GameGlobal = require('GameGlobal');
        window.GameGlobal = new GameGlobal();
    },
  1. 在这个类创建的时候执行如下“添加全局按钮点击音效”的方法。
// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const GameGlobal = cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
    },

    // LIFE-CYCLE CALLBACKS:

    ctor() {
        this.addBtnAudioEffect();
    },

    // onLoad () {},

    start() {

    },

    // update (dt) {},

    // 添加全局按钮点击音效
    addBtnAudioEffect() {
        // 全局按钮响应
        // 添加点击音效
        (function () {

            let btnAudioClip = null;

            cc.resources.load('audio/touch', cc.AudioClip, (err, clip) => {
                if (err) {
                    cc.error(err.message || err);
                    return;
                }

                btnAudioClip = clip;
            });

            let Super = function () { };
            Super.prototype = cc.Button.prototype;
            //实例化原型
            Super.prototype._onTouchEnded = function (t) {
                if (this.interactable && this.enabledInHierarchy) {

                    if (btnAudioClip && btnAudioClip instanceof cc.AudioClip) {
                        let audioID = cc.audioEngine.play(btnAudioClip, false, 0.5);
                    }

                    if (this._pressed) {
                        cc.Component.EventHandler.emitEvents(this.clickEvents, t);
                        this.node.emit('click', this);
                    }
                    this._pressed = !1;
                    this._updateState();
                    t.stopPropagation();
                }
            };
        })();
    },
});

上一篇 下一篇

猜你喜欢

热点阅读