creator ts數組

const {ccclass, property} = cc._decorator;

@ccclass
export default class FrameAnim extends cc.Component {

    @property({type: [cc.SpriteFrame], tooltip:"幀動畫圖片數組"})
    spriteFrames : Array<cc.SpriteFrame> = [];

    @property({tooltip:"每一幀的時長"})
    duration : number = 0.1;

    @property({tooltip:"是否循環播放"})
    loop : boolean = false;
    
    @property({tooltip:"是否在加載的時候就開始播放"})
    playOnload : boolean = false;

    // 播放完後的回調函數
    private endFunc : any = null;
    // 動畫播放需要的精靈組件
    private sprite : cc.Sprite;
    // 動畫播放的狀態,正在播放還是停止
    private isPlaying : boolean = false;
    // 記錄已經播放的時間
    private playTime : number = 0;

    onLoad () {
        // 獲取當前動畫組件掛載的節點上的Sprite組件,如果沒有則添加
        this.sprite = this.node.getComponent(cc.Sprite);
        if(!this.sprite){
            this.sprite = this.node.addComponent(cc.Sprite);
        }

        // 判斷是否是預加載播放
        if(this.playOnload){
            if(this.loop){
                this.playLoop();        // 循環播放
            }else{
                this.playOnce(null);    // 只播放一次
            }
        }
    }

    public playLoop() : void {
        this.initFrame(true, null);
    }   

    public playOnce(endf : any) : void {
        this.initFrame(false, endf);
    }

    private initFrame(loop:boolean, endf : any) : void{
        if(this.spriteFrames.length <= 0){
            return;
        }
        this.isPlaying = true;
        this.playTime = 0;
        this.sprite.spriteFrame = this.spriteFrames[0];
        this.loop = loop;
        this.endFunc = endf;
    }

    start () {

    }

    update (dt) {
        if(!this.isPlaying){
            return;
        }

        // 累計時間,通過時間計算應該取哪一張圖片展示
        this.playTime += dt;
        let index : number = Math.floor(this.playTime / this.duration);

        if(this.loop){  // 循環播放
            if(index >= this.spriteFrames.length){
                index -= this.spriteFrames.length;
                this.playTime -= (this.duration * this.spriteFrames.length);
            }
            this.sprite.spriteFrame = this.spriteFrames[index];
        }else{          // 播放一次
            if(index >= this.spriteFrames.length){
                this.isPlaying = false;
                // 如果有回調函數的處理,則調用回調函數
                if(this.endFunc){
                    this.endFunc();
                }
            }else{
                this.sprite.spriteFrame = this.spriteFrames[index];
            }
        }
    }
}

 

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