cocos2dx3.1 texturepacker播放动画

来源:互联网 发布:unity3d手游大全 编辑:程序博客网 时间:2024/06/09 08:00

先使用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

0 0