cocos creator 按鈕的通用腳本

creator 默認的按鈕狀態有四種: NONE 、 COLOR 、 SPRITE 、 SCALE

這裏的SCALE默認的是點擊放大的效果,但在寫代碼的時候可能會要求實現點擊縮小

爲了方便添加,我們自定義腳本,添加到按鈕上即可。 這裏還可以直接在腳本里添加按鈕點擊音效 。

/**
 * @ 按鈕通用控制腳本
 * @ 使用方法:直接添加到按鈕控件即可 縮放參數可以自己調整
 */

const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property
    pressedScale: number = 0.8;

    @property
    transDuration: number = 0.1;

    @property
    audio:number = 0;

    initScale: number = 0;

    onLoad () {
        var that = this;
        this.initScale = this.node.scale;

        function onTouchDown (event) {
            let scaleDownAction = cc.scaleTo(that.transDuration, that.pressedScale);
            let btnScale = event.target.getComponent('ButtonScaler');
            this.stopAllActions();
            //這裏可以添加音效
            this.runAction(scaleDownAction);
        }

        function onTouchUp (event) {
            let scaleUpAction = cc.scaleTo(that.transDuration, that.initScale);
            this.stopAllActions();
            this.runAction(scaleUpAction);
        }

        this.node.on('touchstart', onTouchDown, this.node);
        this.node.on('touchend', onTouchUp, this.node);
        this.node.on('touchcancel', onTouchUp, this.node);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章