cocos2dx3.1 texturepacker播放動畫

先使用texturepacker把所需要使用的幀動畫打包成一張圖片和一個plist文件。使用大圖的好處就是可以一次性載入圖片,然後通過plist文件確定圖片的位置,在內存中尋找圖片數據,這就減少了I/O操作,使效率大大提高。但是相對來說圖片的大小變大了,因爲中間多了很多的空白的地方。這就是算法分析中時間與空間的矛盾吧。

然後使用如下的代碼播放動畫:

//獲得精靈幀的實例,並通過plist文件載入精靈幀

SpriteFrameCache* cache = SpriteFrameCache::getInstance();
cache->addSpriteFramesWithFile("bear.plist");

//把所有的精靈幀放入Vector數組中
Vector<SpriteFrame*> frameArray;
for (int i = 0; i < 3; i++)
{
string name("bear");
char text[8];
sprintf(text,"%d",i);
string temp(text);
name += temp + ".png";
SpriteFrame* frame = cache->getSpriteFrameByName(name);
frameArray.pushBack(frame);
}

//定義第一個精靈,後續使用這個精靈播放動畫
Sprite* sprite = Sprite::createWithSpriteFrameName("bear0.png");
sprite->setPosition(ccp(400,200));
this->addChild(sprite);

//從數組中獲得精靈幀,並獲得Animation的實例,後面的兩個參數分別是每一次循環的間隔時間,和循環的次數
Animation* animation = Animation::createWithSpriteFrames(frameArray,0.2f);

//播放動作
sprite->runAction(RepeatForever::create(Animate::create(animation)));

使用最新的quick cocos的lua代碼如下:(原理是一樣的)

function MainScene:runAnimation()
-- body
print("runAnimation()")
local  cache = cc.SpriteFrameCache:getInstance()
if cache ~= nil then
--todo
print("cache is null")
end
cache:addSpriteFrames("bear.plist")
print("addspriteframe")
local array = {}
for i = 1,3 do
local str = "bear" .. tostring(i-1) .. ".png"
array[i] = cc.SpriteFrameCache:getInstance():getSpriteFrame(str)
end
local sprite = cc.Sprite:createWithSpriteFrame(array[3])
sprite:setPosition(500,200)
self:addChild(sprite)
local animation = cc.Animation:createWithSpriteFrames(array,0.2)
sprite:runAction(cc.RepeatForever:create(cc.Animate:create(animation)))
end

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章