希望可以幫到剛入坑的新人
直接給小夥伴分享剛完成的源碼:
const {ccclass, property} = cc._decorator;
/**
* @author Maniac.guo
* Everyone should have a dream , what if it came true ?
* @className 動畫元件(動态建立動畫Animation)
* @data 2018年5月18日
* @mailbox [email protected]
*/
@ccclass
export class AnimationComponent extends cc.Component {
@property(cc.SpriteAtlas)
sprAtlas:cc.SpriteAtlas = null;
@property(Number)
wrapMode:cc.WrapMode = cc.WrapMode.Default;
private _animation:cc.Animation;
public onPlayCallBack:Function = null;
public onStopCallBack:Function = null;
public onFinishedCallBack:Function = null;
onLoad () {
this._animation = this.node.getComponent(cc.Animation);
// console.log(this.sprAtlas);
this.setAnimation();
}
public setAnimation() : void {
let self = this;
if(this.sprAtlas){
let frames:[cc.SpriteFrame] = this.sprAtlas.getSpriteFrames();
let clip:cc.AnimationClip = cc.AnimationClip.createWithSpriteFrames(frames,frames.length);
clip.name = "anim_001";
clip.speed = 0.5;
clip.sample = 60;
clip.wrapMode = this.wrapMode;
this._animation.addClip(clip);
}
if(this._animation){
this._animation.on("play",this.onPlay,this);
this._animation.on("stop",this.onStop,this);
this._animation.on("finished",this.onFinished,this);
}
}
// public loadAnima( texturePath:string = "res/game/5026.png" ) : void {
// let self = this;
// cc.loader.loadRes(texturePath, cc.SpriteAtlas, function(error , atlas:cc.SpriteAtlas ){
// let frames:[cc.SpriteFrame] = atlas.getSpriteFrames();
// let clip:cc.AnimationClip = cc.AnimationClip.createWithSpriteFrames(frames,frames.length);
// clip.name = "anim_001";
// clip.speed = 0.5;
// clip.sample = 60;
// clip.wrapMode = self.wrapMode;
// self._animation.addClip(clip);
// });
// }
public playAnimation( wrapMode:cc.WrapMode = cc.WrapMode.Default, speed:number = 0.5, sample:number = 60 ) : void {
if(this._animation){
if(this.node){
this.node.active = true;
}
let animState:cc.AnimationState = this._animation.getAnimationState("anim_001");
animState.clip.wrapMode = wrapMode;
animState.clip.speed = speed;
animState.clip.sample = sample;
this._animation.play("anim_001");
}
}
public stopAnimation() : void {
if(this._animation){
this._animation.stop("anim_001");
}
}
private onPlay() : void {
if(this.onPlayCallBack){
this.onPlayCallBack();
}
}
private onStop() : void {
if(this.onStopCallBack){
this.onStopCallBack();
}
}
private onFinished() : void {
if(this.onFinishedCallBack){
this.onFinishedCallBack();
}
if(this.node){
this.node.active = false;
}
}
onDestroy () {
if(this._animation){
this._animation.off("play",this.onPlay,this);
this._animation.off("stop",this.onStop,this);
this._animation.off("finished",this.onFinished,this);
}
if(this.onPlayCallBack){
this.onPlayCallBack = null;
}
if(this.onStopCallBack){
this.onStopCallBack = null;
}
if(this.onFinishedCallBack){
this.onFinishedCallBack = null;
}
}
}
使用方法:
顯示效果:
寫在最後,本人使用的編輯器是cocos 1.9版本, 昨天在編輯器裡面編輯動畫的時候,發現編輯器有BUG, 往編輯器動畫裡面拖圖檔,不管怎麼拖,又還原成之前的圖檔, 我都想咂電腦了。
是以今天自己動手寫一個動态建立動畫的元件,算是對自己的安慰了。