cocos2dx中創建動畫的三種方法


1.最最原始的方法,先創建動畫幀,再創建動畫打包(animation),再創建動畫(animate)

第一步:

創建動畫幀:CCSpriteFrame,依賴於原始的資源圖片(xx.png,xx.jpg)

CCSpriteFrame *frame1=CCSpriteFrame::create("1.png");

CCSpriteFrame *frame2=CCSpriteFrame::create("2.png");

CCSpriteFrame *frame3=CCSprteFrame::create("3.png");

...

第二步:創建動畫打包,CCAnimation,依賴於創建好的動畫幀,CCSpriteFrame

CCAnimation *animation=CCAnimation::create();

animation->addSpriteFrame(frame1);

animation->addSpriteFrame(frame2);

animation->addSpriteFrame(frame3);

...

設置幀動畫之間的播放間隔

animation->setDelayPerUnit(0.2);

設置幀動畫循環播放的次數

animation->setLoops(5);//-1表示無限循環

 

第三步:創建真正的動畫:animate,依賴於動畫打包,CCAnimation

CCAnimate *animate=CCAnimate::create(animation);

執行動畫:spr->runAction(animate);

//animation->addSpriteFrameWithFileName(CCString::createWithFormat("animation/p_2_0%d.png", i + 1)->getCString());//通過圖片直接創建幀,這是對上面的一種簡化,但是沒法利用幀緩存,效率不高

 

第二種創建動畫的方法:

使用幀動畫緩存:CCSpriteFrameCache,主要是簡化了從原始圖片一幀一幀的加載到內存的步驟

第一步:創建圖片幀緩存,依賴於打包好的xx.plist圖片文件

CCSpriteFrameCache::sharedFrameCache()->addSpriteFramesWithFile("xx.plist");

第二步:將圖片幀緩存中的圖片幀通過循環加入到CCArray數組中(容器),需要先創建好容器

CCArray *array=CCArray::create();

for(int i=0;i<n;i++)

{

  CCString *str=CCString::createWithFormat("%d.png",i+1);

  CCSpriteFrame *frame=CCSpriteFrameCache::sharedFrameCache()->spriteFrameByName(str);//通過圖片幀的名字從圖片幀緩存中獲得圖片幀

  array->addObject(str);//將圖片幀加入數組容器中

}

CCAnimation *animation=CCAnimation::createWithSpriteFrames(array);//通過圖片幀數組來創建動畫打包

animation->setDelayUnit(0.2);

animation->setLoops(-1);

CCAnimate *animate=CCAnimate::create(animation);

spr->runAction(animate);

 

第三種創建幀動畫的方法:

不需要先加載到容器(CCArray)中存起來,直接加入幀動畫打包中即可.

第一步:創建幀動畫緩存CCSpriteFrameCache

CCSpriteFrameCache::sharedFrameCache()->addSpriteFramesWithFile(xx.plist);

CCAnimation *animation=CCAnimation::create();

for(int i=0;i<n;i++)

{

  CCString str=CCString::createWithFormat("%d",i++);

  animation->addSpriteFrame(CCSpriteCache::sharedFrameCache()->spriteFrameByName(str->getCstring()));

}

animation->setDelayUnit(0.2);

animation->setLoops(-1);

CCAnimate *animate=CCAnimate::create(animation);

spr->runAction(animate);

第三種方法是結合了第一種和第二種方法優點,省去了先獲取圖片幀放入容器中,再統一從CCArray中提取圖片幀來創建動畫打包的步驟.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM