Cocos Creator使用序列帧、骨骼创建动画

一、导入资源

动画资源放到resources/model文件夹下,没有则对应新建一个,当然,也可以是其他路径,代码做对应修改就行(下同);

二、创建节点

创建一个节点,并将动画组件和脚本都放在同一个节点;

三、使用序列帧创建动画

1)序列帧+图集(一个.plist文件和一个同名的图片文件如.png)

  1. 初始化动画组件及点击事件(用于测试)
animComponent:cc.Animation = null;
onload(){
          
   
		// 获取节点上的cc.Animation组件(此处动画组件和脚本都在同一个节点,不同节点对应修改)
	this.animComponent = this.node.getComponent(cc.Animation);

		// 点击该节点播放动画
	this.node.on("touchend",()=>{
          
   
    	this.animComponent.play(“animName”);
	})
}
  1. 加载图集(文件放在对应的路径下,loadRes()的路径参数默认不用写resources)
cc.loader.loadRes(“model/model”, cc.SpriteAtlas, (err,res)=>{
          
   
		if(!err){
          
   
			this.initClips(res);
		}
}
  1. 创建动画
// 创建动画
initClips(res){
          
   
		// 获取图集res内的所有帧,获得的atlas是一个图片对象数组
		let atlas = res.getSpriteFrames();
		// 使用一组序列帧图片来创建动画,参数10是播放速率
		let clip = cc.AnimationClip.createWithSpriteFrames(atlas,10)
		// 设置动画循环模式(此处设为一直循环)
		clip.wrapMode = cc.WrapMode.Loop;
		// 将动画序列添加到动画组件中,其中animName是自定义的动画名称
		this.animComponent.addClip(clip,”animName”);
}

2)序列帧单独放一个文件夹 资源路径示例

1.初始化动画组件及点击事件(用于测试)

animationComponent:cc.Animation = null;
onload(){
          
   
		// 获取节点上的cc.Animation组件(此处动画组件和脚本都在同一个点,不同节点对应修改)
		this.animComponent = this.node.getComponent(cc.Animation);

		// 点击该节点播放动画
		this.node.on("touchend",()=>{
          
   
    		this.animComponent.play(“animName”);
		})
}

2.加载序列帧图片路径(文件放在对应的路径下,loadRes()的路径参数默认不用写resources)

let path = “model/hero”;
cc.loader.loadResDir(path, cc.SpriteFrame, (err,res,url)=>{
          
   
		if(!err){
          
   
			this.initClips(path,res,url);
		}
}

3.创建动画

// 创建动画
initClips(path,res,url){
          
   
		// 获取res内的所有帧,获得的sprites是一个图片对象数组
		let sprites = [];
		for(let i = 1;i < res.length;i++){
          
   
			if(i < 10)
				sprites.push(res[url.indexOf(path + “/0” + i)]);
			if(i >= 10)
				sprites.push(res[url.indexOf(path + “/” + i)]);
		}
		// 使用一组序列帧图片来创建动画,参数res.length是播放速率
		let clip = cc.AnimationClip.createWithSpriteFrames(sprites, res.length)
		// 设置动画循环模式(此处设为只播放一次)
		Clip.wrapMode = cc.WrapMode. Normal;
		// 将动画序列添加到动画组件中,其中animName是自定义的动画名称
		this.animComponent.addClip(clip,”animName”);
}

四、使用骨骼动画

资源路径示例

脚本和组件放同一个节点(不强制)

1.初始化动画组件(用于测试)

skeComponent:sp.Skeleton;
onload(){
          
   
// 绑定节点上的骨骼动画组件
     this.skeComponent = this.node.getComponent(sp.Skeleton);
}

2.加载骨骼动画路径(文件放在对应的路径下,loadRes()的路径参数默认不用写resources)

let path = “model/ hero1/r_0003”;
cc.loader.loadResDir(path, sp.SkeletonData, (err, skeData)=>{
          
   
		if(!err){
          
   
			// 绑定数据
     		this.skeComponent.skeletonData = skeData;
     		// 设置播放动画
         	this.skeComponent.setAnimation(0,"move",true);
		}
}

骨骼动画的动画名称(设置时用到):可以将动画拉到组件上,查看每个动画的名称

经验分享 程序员 微信小程序 职场和发展