幀動畫組件的封裝

一、建立精靈組件,並指定對應的第一張圖片數組

二、建立腳本,而且綁定在精靈組件上,腳本以下oop

cc.Class({
    extends: cc.Component,
    properties: {
        cows: {
            type: cc.SpriteFrame,
            default: []  //注意,這邊是個數組,動畫的每一幀拖入便可
        },
        duration: 0.2,
        loop: false,
        preload: false
    },
    onLoad() {
        //獲取牛的信息
        this.cow = this.getComponent(cc.Sprite);
        if (!this.cow) {
            this.cow = this.addComponent(cc.Sprite);
        }
        //是否正在播放
        this.isPlaying = false;
        //播放的時候時間計數
        this.countTime = 0;
        //是否預加載播放
        if (this.preload) {
            //是否循環播放
            if (this.loop) {
                this.playLoop()
            } else {
                this.playOnce();
            }
        }
    },
    start() {
    },
    update(dt) {
        this.play_fn(dt);
    },
    playLoop(fn) {
        if (this.cows.length < 1) {
            return;
        }
        this.loop = true;
        this.isPlaying = true;
        this.cow.spriteFrame = this.cows[0];
        this.fn = fn;
    },
    playOnce: function (fn) {
        if (this.cows.length < 1) {
            return;
        }
        this.loop = false;
        this.isPlaying = true;
        this.cow.spriteFrame = this.cows[0];
        this.fn = fn;
    },
    play_fn(dt) {
        if (this.isPlaying) {
            this.countTime += dt;
            let index = Math.floor(this.countTime / this.duration);
            //假如只是播放一次的狀況
            if (!this.loop) {
                if (index >= this.cows.length) {
                    this.isPlaying = false;
                    this.fn && this.fn();
                } else {
                    this.cow.spriteFrame = this.cows[index];
                }
            } else {//假如是循環播放的狀況
                while (index >= this.cows.length) {
                    index -= this.cows.length;
                    this.countTime -= (this.cows.length * this.duration);
                }
                this.cow.spriteFrame = this.cows[index];
                this.fn && this.fn();
            }
        }
    }

});

三、在根節點上定義新的腳本,具體內容以下動畫

let cow_frame = require('test_scene');
cc.Class({
    extends: cc.Component,

    properties: {
        ani: {
            //注意:在所對應的界面裏,拖入動畫的精靈節點,而不是對應的腳本
            type: cow_frame,
            default: null
        }
    },

    onLoad() {
    //注意,不要在這個生命週期裏面調用引入的組件,有可能還未加載出來,這樣容易報錯 }, start() {
//調用接口 this.ani.playOnce(function () { console.log('are you ok???'); }); this.ani.playLoop(); }, update() { }, });
相關文章
相關標籤/搜索