东西不难,就是自己实现一下
在工作中因要定制一个动画播放,所以自己简单的利用了cocos的update函数写了一个最粗糙版本的播放序列帧,但是只能播放一个序列帧动画,所以改进了一下,改成了可以播放多个,代码如下
update(dt) {
this._super(dt)
for (let index = 0; index < this._animationArray.length; index++) {
if (!this._animationArray[index].isPlay) continue;
if (this._animationArray[index].timeIndex < this._animationArray[index].timeRange) {
this._animationArray[index].timeIndex += dt
continue;
}
else {
let l = this._animationArray[index].frames.length
if (this._animationArray[index].frameIndex >= l) {
this._animationArray[index].isPlay = false
this.deletAnim = true;
this.deletIndex = index;
if(this._animationArray[index].over){
this._animationArray[index].comp.spriteFrame = null
}
continue;
}
this._animationArray[index].comp.spriteFrame = this._animationArray[index].frames[this._animationArray[index].frameIndex]
this._animationArray[index].frameIndex++
this._animationArray[index].timeIndex = 0;
if (this._animationArray[index].frameIndex >= l && this._animationArray[index].loop) {
this._animationArray[index].frameIndex = 0;
}
}
}
if (this.deletAnim) {
this.deletAnim = false;
this.removeAnim(this.deletIndex)
}
},
removeAnim(index) {
this._animationArray.splice(index, 1)
},
playAnimation(comp, anims, time, over = true, loop = false) {
//isPlay 是否播放
//timeRange 切换帧时间长度
//timeIndex 当前时间长度
//comp 当前切换帧的组件
//frames 动画帧数组
//frameIndex 当前第几帧
//loop 是否循环
//over 是否播放结束后切换空帧
let id = this._animindex++;
let a = { isPlay: true, timeRange: time / anims.length, timeIndex: 0, comp: comp, frames: anims, frameIndex: 0, loop: loop, over: over, id: id }
this._animationArray.push(a)
return id;
},
说一下当前方法的让我不满意之处,就是依靠了update,但是我还是想着不依靠updata来实现这个功能,参考了cocos源码的action被继承的对象发现,使用了递归来实现这个功能,那么继续实现的话,就需要关键的帧间隔时间,查阅了资料后发现,window.requestAnimationFrame这个方法,可以在浏览器进行重绘前把传入的函数调用,在cocos的ccgame里也确实调用了,上图:
清楚了帧间隔是怎么调用的,那么就不需要自己再调用window.requestAnimationFrame这个方法了,既帧间隔直接用dt获取即可