帧动画是游戏中特效表现的必修课。那么我们使用代码要怎么样来实现帧动画的效果呢?
第一步、定义帧动画的一些属性:
定义一些属性,方便编辑器上调试效果:帧动画的图片数组、2帧之间的时间间隔、是否循环、是否加载时播放等;
properties: {
//帧动画的图片数组
sprite_frames: {
type: cc.SpriteFrame,
default: [],
},
//时间间隔
duration: 0.1,
//是否循环
is_loop: false,
//是否加载时播放
play_onload: false,
},
第二步、两个函数:循环播放、一次播放
//循环播放
play_loop: function(){
if(this.sprite_frames.length <= 0){
return;
}
this.is_loop = true;
this.end_func = null;
this.is_playing = true;
this.sprite.spriteFrame = this.sprite_frames[0];
},
//一次播放
play_once: function(end_func){
if(this.sprite_frames.length <= 0){
return;
}
this.end_func = end_func;
this.is_loop = false;
this.is_playing = true;
this.sprite.spriteFrame = this.sprite_frames[0];
},
第三步、加载load
onLoad () {
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.is_loop){
this.play_loop();
}
else{
this.play_once();
}
}
},
第四步、图片的刷新控制
update (dt) {
if(!this.is_playing){
return;
}
this.play_time += dt;
var index = Math.floor(this.play_time / this.duration);
if(!this.is_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];
}
},
测试
// Learn cc.Class:
// - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
// - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
// - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
// - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
// - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html
var frame_anim = require("frame_anim");
cc.Class({
extends: cc.Component,
properties: {
// foo: {
// // ATTRIBUTES:
// default: null, // The default value will be used only when the component attaching
// // to a node for the first time
// type: cc.SpriteFrame, // optional, default is typeof default
// serializable: true, // optional, default is true
// },
// bar: {
// get () {
// return this._bar;
// },
// set (value) {
// this._bar = value;
// }
// },
anim:{
type: frame_anim,
default: null,
},
},
// LIFE-CYCLE CALLBACKS:
// onLoad () {},
start () {
// this.anim.play_once(function(){
// console.log("play_once~~~~");
// });
this.anim.duration = 0.2;
this.anim.play_loop();
},
// update (dt) {},
});