import { _decorator, Component, SpriteFrame, Sprite} from 'cc'; import { Game } from '../game/Game'; const { ccclass, property } = _decorator; @ccclass('FrameAnimation') export class FrameAnimation extends Component { @property({type:[SpriteFrame],tooltip: "播放的帧动画类"}) public playSFArray: Array = []; //每一帧的时长 private duration: number = 0.1; //播放完后的回调函数 private endFunc : Function = null; //播放到第几帧回调函数 private playIdxFunc : Function = null; //播放到第几帧回调函数 private idx : number = 0; //是否播放帧动画 private isPlayAnim : boolean = false; //记录已经播放的时间 private playTime : number = 0; //是否循环播放 private loop : boolean = true; //播放的精灵 播放的帧动画 private currnSprite : Sprite = null!; //播放帧图片数据 public playSFs: Array = []; /** * 播放帧动画 * @param noSp * @param clipSFs * @param isLoop * @param callback */ public play(s: number = this.duration,loop: boolean = true, endf: Function = ()=>{},playFun: Function = ()=>{},idx: number = 0){ if(!loop){ if(this.isPlayAnim){return} } if(this.playSFArray.length > 0){ this.playSFs = this.playSFArray; } if(!this.currnSprite){ this.currnSprite = this.node.getComponent(Sprite); } if(this.playSFs.length > 0){ this.isPlayAnim = true; this.playTime = 0; this.loop = loop; this.duration = s / this.playSFs.length; this.endFunc = endf; this.idx = idx; this.currnSprite.spriteFrame = this.playSFs[0]; this.playIdxFunc = playFun; }else{ this.isPlayAnim = false; } } protected update(deltaTime: number) { if(!this.isPlayAnim ||!this.currnSprite ||!this.currnSprite.node.active){ return; } let g:Game = Game.I; if(g && g.isPause){ return; } //累计时间,通过时间计算应该取哪一张图片展示 this.playTime += deltaTime; let index : number = Math.floor(this.playTime / this.duration); if(this.loop){ // 循环播放 if(index >= this.playSFs.length){ index -= this.playSFs.length; this.playTime -= (this.duration * this.playSFs.length); } this.currnSprite.spriteFrame = this.playSFs[index]; }else{ //播放一次 if(index >= this.playSFs.length){ this.isPlayAnim = false; //如果有回调函数的处理,则调用回调函数 this.endFunc?.(); }else{ this.currnSprite.spriteFrame = this.playSFs[index]; } if(this.playIdxFunc && this.idx == index){ this.playIdxFunc(); } } } }