Cocos2d-HTML5--人物動畫
阿新 • • 發佈:2019-01-31
首先看下人物動畫效果
實現步驟
- 製作人物動作圖片
- 在程式碼中提取動作圖片
- 將圖片組成每一種狀態的動作
- 實現不同動作間的切換
製作人物動作圖片
相關技術 Plist
通過將小的圖片組合成一張大圖,可以減少讀取圖片的次數來優化效能
Plist製作
使用cocos2d studio 自帶的功能,新建一個合圖,然後匯入資源,再匯出合圖即可
在程式碼中提取動作圖片
- 將圖片資源在src/resource.js 中註冊
- 將plist資源加入快取
- 從快取中提取每一張圖片資源
resource.js
var img_plist = 'img.plist';
var img_png = 'img.png';
var background = 'background.jpg';
var g_resources = [
//image
img_plist,
img_png,
background
];
將plist資源加入快取
cc.spriteFrameCache.addSpriteFrames(img_plist);
讀取圖片資源
方法一:
//注意這裡的圖片名是在製作plist之前的原檔案的檔名,而且需要加#
this.sprite = new cc.Sprite("#person1.png");
方法二:
//製作動畫幀的常用方法
var str = "person" + i + ".png";
frame = cc.spriteFrameCache.getSpriteFrame(str);
將圖片組成每一種狀態的動作
製作動畫組
//running left 動作初始化
for (var i = 1; i <= 4; i++) {
str = "person" + i + ".png";
frame = cc.spriteFrameCache.getSpriteFrame(str);
animFrames.push(frame);
}
this .runRightAnimation = new cc.Animation(animFrames, 0.1);
//running right 動作初始化
animFrames = [];
for (var i = 5; i <= 8; i++) {
str = "person" + i + ".png";
frame = cc.spriteFrameCache.getSpriteFrame(str);
animFrames.push(frame);
}
this.runLeftAnimation = new cc.Animation(animFrames, 0.1);
//jump 向右
animFrames = [];
for (var i = 9; i <= 10; i++) {
str = "person" + i + ".png";
frame = cc.spriteFrameCache.getSpriteFrame(str);
animFrames.push(frame);
}
this.jumpRightAnimation = new cc.Animation(animFrames, 0.25);
//jump 向右
animFrames = [];
for (var i = 11; i <= 12; i++) {
str = "person" + i + ".png";
frame = cc.spriteFrameCache.getSpriteFrame(str);
animFrames.push(frame);
}
this.jumpLeftAnimation = new cc.Animation(animFrames, 0.25);
執行動畫
this.sprite.runAction(cc.animate(this.runRightAnimation).repeatForever());
實現不同動作間的切換
cocos2d 在實現人物動畫的時候使用的是action,由於我們需要保持人物的跑動狀態而使用了.repeatForever()方法,那麼在切換動作的時候就會出現一點問題,即在向右跑動時再向左跑的時候實際上向右跑動的動作動畫並沒有停止,就會出現兩種動畫疊加的情況。
解決方法:
在每次執行動作動畫之前都執行這句程式碼
this.sprite.stopAllActions();
但是這樣又帶來了新的問題,當按住向右不放時,會不停的觸發this.sprite.stopAllActions(),則動畫始終處於第一幀,解決方法,使用狀態機
goRight: function(){
switch (this.runState){
case 1:
//原本向右,則保持原本的動畫不變
break;
case 2:
//原本向左,則停止向右的動作,變為向左
this.sprite.stopAllActions();
this.sprite.runAction(cc.animate(this.runRightAnimation).repeatForever());
break;
default :
this.sprite.runAction(cc.animate(this.runRightAnimation).repeatForever());
break;
}
this.sprite.runAction(new cc.MoveBy(0.2, cc.p(this.stepLength,0)));
this.runState = 1;
},