轉載此文的目的是為了自己以後尋找方便~
原始出處
一、引子哦,好吧,我一直比較吐槽cocos2d-x那個動畫載入方式,記得我在《cocos2d-x學習筆記04:簡單動畫》中寫的,一個簡單動畫的載入,就需要寫十幾行代碼。
- CCSize s = CCDirector::sharedDirector()->getWinSize();
-
- //#1:產生動畫需要的資料類
- CCTexture2D *texture=CCTextureCache::sharedTextureCache()->addImage("pic2476.png");
- CCSpriteFrame *frame0=CCSpriteFrame::frameWithTexture(texture,CCRectMake(32*0, 48*0, 32, 48));
- CCSpriteFrame *frame1=CCSpriteFrame::frameWithTexture(texture,CCRectMake(32*1, 48*0, 32, 48));
- CCSpriteFrame *frame2=CCSpriteFrame::frameWithTexture(texture,CCRectMake(32*2, 48*0, 32, 48));
- CCSpriteFrame *frame3=CCSpriteFrame::frameWithTexture(texture,CCRectMake(32*3, 48*0, 32, 48));
-
- CCMutableArray<CCSpriteFrame*> *animFrames = new CCMutableArray<CCSpriteFrame*>(4);
- animFrames->addObject(frame0);
- animFrames->addObject(frame1);
- animFrames->addObject(frame2);
- animFrames->addObject(frame3);
-
- CCAnimation *animation = CCAnimation::animationWithFrames(animFrames, 0.2f);
- animFrames->release();
- //#2:初始化並設定Sprite
- CCSprite *sprite = CCSprite::spriteWithSpriteFrame(frame0);//設定一個初始frame
- sprite->setPosition( ccp( s.width/2, s.height/2) );
- addChild(sprite);
-
- //#3:使用animation產生一個動畫動作animate
- CCAnimate *animate = CCAnimate::actionWithAnimation(animation, false);
- sprite->runAction(CCRepeatForever::actionWithAction(animate));//重複播放
恩,這其中載入的代碼佔了好多,我們可以通過刷迴圈簡化。也就是說,理論上至少可以減少大約一半的量。
但是你刷迴圈簡化有個前提:png的排列必須十分規律,否則是無法使用的。並且,不同的動作有不同的幀數和不同的delay,你每個都要自己寫。這毫無疑問是一個非常繁瑣的過程。
於是我開發了一個工具AnimatePacker,專門解決這個問題。顧名思義,AnimatePacker就是一個動作打包的小工具,可以很方便的自己編輯動作。由此節省大量的程式編碼。
二、AnimatePacker使用
這個工具要和TexturePacker等工具配合使用,因為需要他們來提供plist。另外,要使用這個工具,必須先熟悉TexturePacker等工具,以及cocos2d-x的動畫代碼。
開啟介面,一目瞭然。熟悉cocos2d-x編程的人,肯定知道這四個框是什麼。
Plists:所有的Plist列表,拖動plist檔案到AnimatePacker視窗上,就可以載入。Animations:所有的動作列表,點擊“攝像機”按鈕可以建立動作,雙擊可以編輯Name和Delay。SpriteFrames:當前Animation對應的SpriteFrames列表,拖動可以排序。Sprites:所有的備選Spirte,你可以拖動Spirte到SpriteFrames框下面。
簡單使用步驟:1.拖動plist檔案到AnimatePacker視窗2.點擊攝像機,產生新的Animation,在Animations框中編輯Name和Delay3.從Sprites裡拖動Sprite到SpriteFrames,拖動SpriteFrame可排序
就這樣不斷的編輯和產生即可。最後,我們點擊儲存,就可以輸出一個自己的xml。這裡我們就叫他“1111.xml”好了。
三、解析代碼使用
解析1111.xml需要用到下面三個檔案:
- AnimatePacker.h
- AnimatePacker.cpp
- Singleton.h //需要匯入的支援檔案
解析代碼非常簡單,只有兩個介面:
- void AnimatePacker::loadAnimate(char *path);//載入xml裡面的動畫
- cocos2d::CCAnimate* AnimatePacker::getAnimate(char *name);//擷取指定名稱的動畫
具體寫起來大約是這樣的:
- AnimatePacker::getInstance()->loadAnimate("1111.xml");
- CCSprite *sprite=CCSprite::spriteWithSpriteFrameName("bomb_dead0.png");
- sprite->setAnchorPoint(CCPointZero);
- sprite->setPosition(ccp(size.width/2, size.height/2));
- sprite->runAction(CCRepeatForever::actionWithAction(AnimatePacker::getInstance()->getAnimate("aaa")));
- addChild(sprite,1);
AnimatePacker採用Qt編寫,也就是說可以跨多個平台。但目前只有win32版,因為mac下我還沒配qt開發環境,稍後提供。這個工具現在是測試版,歡迎提供bug和改進意見,直接在下面回複就行了。