文字打印机效果组件--源代码分享

文字打印机的简单实现,分享下代码。

const { ccclass, property,executeInEditMode,requireComponent,disallowMultiple } = cc._decorator;

@ccclass
@executeInEditMode
@requireComponent(cc.Label)
@disallowMultiple
export default class TypewriterLabel extends cc. Component {
    @property({multiline: true,formerlySerializedAs: '_N$string',visible:false})
    private _msg = '';

    @property({multiline: true})
    get msg () {
        return this._msg;
    }
    set msg (value) {
        let oldValue = this._msg;
        this._msg = value.toString();

        if (this.msg !== oldValue) {
            this.typingAni();
        }
    }

    private label:cc.Label = null;
    private callback:Function = null;
    onLoad(){
        this.fetchRender();
        this.typingAni();
    }

    private fetchRender () {
        let label = this.getComponent(cc.Label);
        if (label) {
            this.label = label;
            this.updateLabel();
            return;
        }
    }

    private updateLabel () {
        if (!this.label) {
            console.error('Failed to update localized label, label component is invalid!');
            return;
        }

        this.label.string = this.msg;
    }

    private typingAni(){
        let self = this;
        let arr = self.msg.split('');
        let len = arr.length;
        let step = 0;
        this.label.string = '';
        setTimeout(function fn(){
            self.label.string += arr[step];
            if(++step == len){
                self.typeEnd();
            }
            else{
                setTimeout(fn,100);
            }
        },100);
    }

    /**
     * 打印显示结束
     */
    private typeEnd(){
        if(this.callback){
            this.callback();
        }
    }

    /**
     * 设置打印显示结束回调
     */
    public setTypeEndCallBack(callback:Function,target:any){
        this.callback = this.callback.bind(target);
    }

使用时直接:
@property( TypewriterLabel )
typeWriter : TypewriterLabel = null;

typeWriter.msg = ‘巴拉巴拉巴拉’;