自行制作帧动画组件
1: creator播放帧动画需要通过动画编辑器去制作;
2: 为了方便控制和使用加入帧动画代码播放组件;
3: 属性设置:
sprite_frames: 帧动画所用到的所有的帧;
duration: 每帧的时间间隔;
loop: 是否循环播放;
play_onload: 是否加载组件的时候播放;
4: 接口设置:
play_once(end_func); // 播放结束后的回掉函数;
play_loop(); // 循环播放;
1: 对的时间播放显示对的图片:
假设以三帧动画为例,时间间隔就是duration,
如果场景中节点传入得是某个系统的类型如sprite,label ,可以定义然后传入
如果是自定义的脚本并挂载在其他节点,定义后,需要在本节点的脚本上写requirexxx
==========================================================
帧动画组件JS:
cc.Class({
extends: cc.Component,
properties: {
// 帧动画的图片, 多张图片,
sprite_frames: {
default: [],
type: cc.SpriteFrame,
},
duration: 0.1, // 帧的时间间隔
loop: false, // 是否循环播放;
play_onload: false, // 是否在加载的时候就开始播放;
},
// use this for initialization
onLoad: function () {
this.end_func = null;//回调函数
this.is_playing = false; // 加一个变量
this.play_time = 0; // 播放的时间
// 获得了精灵组件
this.sprite = this.getComponent(cc.Sprite);
if (!this.sprite) {
this.sprite = this.addComponent(cc.Sprite);
}
if (this.play_onload) { // 如果在加载的时候开始播放
if (this.loop) { // 循环播放
this.play_loop();
}
else { // 播放一次
this.play_once(null);
}
}
},
play_loop: function() {
if (this.sprite_frames.length <= 0) {
return;
}
this.loop = true;
this.end_func = null;
this.is_playing = true; // 正在播放
this.play_time = 0; // 播放的时间
this.sprite.spriteFrame = this.sprite_frames[0];
},
// 需要播放结束以后的回掉, end_func
play_once: function(end_func) {
if (this.sprite_frames.length <= 0) {
return;
}
this.end_func = end_func;
this.loop = false;
this.is_playing = true; // 正在播放
this.play_time = 0; // 播放的时间
this.sprite.spriteFrame = this.sprite_frames[0];
},
// called every frame, uncomment this function to activate update callback
// 每次游戏刷新的时候
update: function (dt) {
if(!this.is_playing) {
return;
}
this.play_time += dt; // 当前我们过去了这么多时间;
var index = Math.floor(this.play_time / this.duration);
// 非循环播放
if (!this.loop) {
if (index >= this.sprite_frames.length) { // 如果超过了,播放结束
this.is_playing = false;
if (this.end_func) {
this.end_func();
}
}
else {
this.sprite.spriteFrame = this.sprite_frames[index]; // 修改当前时刻显示的正确图片;
}
}
else { // 循环播放
while(index >= this.sprite_frames.length) {
index -= this.sprite_frames.length;
this.play_time -= (this.sprite_frames.length * this.duration);
}
this.sprite.spriteFrame = this.sprite_frames[index];
}
},
});
======================================================
组件的运用JS:
var frame_anim = require("frame_anim");
cc.Class({
extends: cc.Component,
properties: {
anim: {
type: frame_anim,
default: null,
}
},
// use this for initialization
onLoad: function () {
},
start: function()
{
this.anim.duration = 1;
this.anim.play_loop();
},
});