Cocos Creator 动画控制
Cocos Creator 3.x
import { Animation, error } from "cc";
export class AnimationUtil {
/**
* 播放动画到指定的sprite帧,并停止
* @param animation cc.Animation组件
* @param frameIndex 帧索引(大于等于0的整数)
* @param clipStateName 动画剪辑状态的名称
*/
public static gotoAndStop(animation: Animation, frameIndex: number, clipStateName: string): void {
if (frameIndex === undefined || isNaN(frameIndex) || frameIndex < 0) {
error("frame 不能是 undefined、NaN、小于0");
}
frameIndex = frameIndex | 0; // 取整
const animState = animation.getState(clipStateName);
animState.stop();
const times: number[] = animState.clip['_tracks'][0]['_channel']['_curve']['_times'];
frameIndex = Math.min(frameIndex, times.length - 1);
const frameTime: number = times[frameIndex];
animState.setTime(frameTime);
animState.sample();
}
}
Cocos Creator 2.x
//即使playOnLoad=true,也必须调用play函数播放一个动画,currentClip属性才会赋值
let animation=this.getComponent(cc.Animation);
animation.playOnLoad=true;
cc.log(animation.currentClip);//ouput: null
animation.play("idle");
cc.log(animation.currentClip.name);//ouput: idle
//每帧都调用play方法播放一个动画时,必须判断要播放的剪辑是否已是当前剪辑,否则会一直播放停止在第一帧
if(animation.currentClip.name!="walk"){
animation.play("walk");
}
let animationState=animation.play("idle");
animationState.time;//动画播放的时间(注意:播放循环的的动画剪辑时,播放完成一遍后不会重置0)
侦听循环的动画剪辑播放完成
let animation=this.getComponent(cc.Animation);
let animationState=animation.play("idle");
animationState.wrapMode=cc.WrapMode.Loop;
animationState.repeatCount=0;//设置循环的次数,0表示只播放一次(则不需要去设置wrapMode)
animation.on("finished",this.onFinished,this);
//private onFinished():void{}
动态修改AnimationClip.speed,AnimationSate.speed,duration不会更新
animState.speed=2;//动态修改时不会受到影响animState.duration,animState.clip.duration
animState.clip.speed=2;//动态修改时不会受到影响animState.duration,animState.clip.duration
在指定帧停止
let animState=this._animation.play("num");
animState.speed=0;
let frameNO=3;//停止的帧编号
let frameTime:number=animState.clip.curveData['comps']['cc.Sprite']['spriteFrame'][frameNO-1].frame;
this._animation.setCurrentTime(frameTime);
//完整指定帧停止的函数:
/**
* 播放动画到指定的sprite帧,并停止
* @param animation cc.Animation组件
* @param frameNO 帧编号(大于0的整数)
* @param clipName 不填写时播放默认动画剪辑
*/
public static gotoAndStop(animation:cc.Animation,frameNO:number,clipName?:string):void{
let frameNO_int=frameNO|0;
if(frameNO_int!==frameNO||frameNO<1){
frameNO=Math.max(frameNO_int,1);
cc.warn("参数 frameNO 应传入正整数");
}
let animState=animation.play(clipName);
const speedRecord=animState.speed;
animState.speed=0;
let spriteFrameDatas:any[]=animState.clip.curveData['comps']['cc.Sprite']['spriteFrame'];
frameNO=Math.min(frameNO,spriteFrameDatas.length);
let frameTime:number=spriteFrameDatas[frameNO-1].frame;
animation.setCurrentTime(frameTime);
animState.stop();
animState.speed=speedRecord;
}