FrameAnimation.ts 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { _decorator, Component, SpriteFrame, Sprite} from 'cc';
  2. import { Game } from '../game/Game';
  3. const { ccclass, property } = _decorator;
  4. @ccclass('FrameAnimation')
  5. export class FrameAnimation extends Component {
  6. @property({type:[SpriteFrame],tooltip: "播放的帧动画类"})
  7. public playSFArray: Array<SpriteFrame> = [];
  8. //每一帧的时长
  9. private duration: number = 0.1;
  10. //播放完后的回调函数
  11. private endFunc : Function = null;
  12. //播放到第几帧回调函数
  13. private playIdxFunc : Function = null;
  14. //播放到第几帧回调函数
  15. private idx : number = 0;
  16. //是否播放帧动画
  17. private isPlayAnim : boolean = false;
  18. //记录已经播放的时间
  19. private playTime : number = 0;
  20. //是否循环播放
  21. private loop : boolean = true;
  22. //播放的精灵 播放的帧动画
  23. private currnSprite : Sprite = null!;
  24. //播放帧图片数据
  25. public playSFs: Array<SpriteFrame> = [];
  26. /**
  27. * 播放帧动画
  28. * @param noSp
  29. * @param clipSFs
  30. * @param isLoop
  31. * @param callback
  32. */
  33. public play(s: number = this.duration,loop: boolean = true, endf: Function = ()=>{},playFun: Function = ()=>{},idx: number = 0){
  34. if(!loop){
  35. if(this.isPlayAnim){return}
  36. }
  37. if(this.playSFArray.length > 0){
  38. this.playSFs = this.playSFArray;
  39. }
  40. if(!this.currnSprite){
  41. this.currnSprite = this.node.getComponent(Sprite);
  42. }
  43. if(this.playSFs.length > 0){
  44. this.isPlayAnim = true;
  45. this.playTime = 0;
  46. this.loop = loop;
  47. this.duration = s / this.playSFs.length;
  48. this.endFunc = endf;
  49. this.idx = idx;
  50. this.currnSprite.spriteFrame = this.playSFs[0];
  51. this.playIdxFunc = playFun;
  52. }else{
  53. this.isPlayAnim = false;
  54. }
  55. }
  56. protected update(deltaTime: number) {
  57. if(!this.isPlayAnim
  58. ||!this.currnSprite
  59. ||!this.currnSprite.node.active){
  60. return;
  61. }
  62. let g:Game = Game.I;
  63. if(g && g.isPause){
  64. return;
  65. }
  66. //累计时间,通过时间计算应该取哪一张图片展示
  67. this.playTime += deltaTime;
  68. let index : number = Math.floor(this.playTime / this.duration);
  69. if(this.loop){ // 循环播放
  70. if(index >= this.playSFs.length){
  71. index -= this.playSFs.length;
  72. this.playTime -= (this.duration * this.playSFs.length);
  73. }
  74. this.currnSprite.spriteFrame = this.playSFs[index];
  75. }else{
  76. //播放一次
  77. if(index >= this.playSFs.length){
  78. this.isPlayAnim = false;
  79. //如果有回调函数的处理,则调用回调函数
  80. this.endFunc?.();
  81. }else{
  82. this.currnSprite.spriteFrame = this.playSFs[index];
  83. }
  84. if(this.playIdxFunc && this.idx == index){
  85. this.playIdxFunc();
  86. }
  87. }
  88. }
  89. }