自行制作幀動畫元件
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();
},
});