帧动画组件的封装

1、创建精灵组件,并指定对应的第一张图片

2、创建脚本,并且绑定在精灵组件上,脚本如下

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();
            }
        }
    }

});

3、在根节点上定义新的脚本,具体内容如下

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() { }, });
原文地址:https://www.cnblogs.com/rickyctbu/p/10091793.html