添加全局按鈕點(diǎn)擊音效

Cocos Creator v2.4.0

起因:做一個(gè)小游戲需要在按鈕點(diǎn)擊的時(shí)候添加一個(gè)音效。
需求:全部的按鈕在點(diǎn)擊的時(shí)候都要播放這個(gè)音效。

  1. 啟動(dòng)場(chǎng)景中加載了一個(gè)全局控制類,可以不加,不重要。
onLoad() {
        const GameGlobal = require('GameGlobal');
        window.GameGlobal = new GameGlobal();
    },
  1. 在這個(gè)類創(chuàng)建的時(shí)候執(zhí)行如下“添加全局按鈕點(diǎn)擊音效”的方法。
// 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) {},

    // 添加全局按鈕點(diǎn)擊音效
    addBtnAudioEffect() {
        // 全局按鈕響應(yīng)
        // 添加點(diǎn)擊音效
        (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;
            //實(shí)例化原型
            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();
                }
            };
        })();
    },
});

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容