可以把常见的Animate的创建方法封装成几个函数,在使用时进行调用。
第一种方法使用do...while循环实现,不需要知道图片的数量,只要有图片的名字就可以,代码如下:
Animate* Create(const char *iName, int iloops, float delay)
{
SpriteFrame* frame = NULL;
Animation* animation = Animation::create();
int index = 1;
// 创建帧对象
do
{
String * name = String::createWithFormat("%s%d.png", iName, index++);
frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(name->getCString());
if (frame == NULL)
{
break;
}
animation->addSpriteFrame(frame);
} while (true);
animation->setDelayPerUnit(delay); // 每帧播放间隔
animation->setRestoreOriginalFrame(true); //播放完成之后回到初始帧
animation->setLoops(iloops);
// 创建动画动作
Animate* action = Animate::create(animation);
return action;
}
第二种方法使用for循环实现,需要知道图片的名字和数量,代码如下:
Animate* Create(const char *iName, int framecount, int iloops, float delay)
{
SpriteFrame* frame = NULL;
Animation* animation = Animation::create();
// 遍历图片帧
for (int index = 1; index <= framecount; index++)
{
String * name = String::createWithFormat("%s%d.png", iName, index);
frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(name->getCString());
animation->addSpriteFrame(frame);
}
animation->setLoops(iloops);
animation->setDelayPerUnit(delay);
animation->setRestoreOriginalFrame(true); //播放完成之后回到初始帧
Animate* animate = Animate::create(animation);
return animate;
}
第三种方法是先使用Vector对帧进行封装,然后创建Animation,接着创建Animate,代码如下:
Animate* Create(const char *iName, int framecount, int iloops, float delay){
SpriteFrame* frame = NULL;
Vector<SpriteFrame*> frameVec;
for (int index = 1; index <= framecount; index++){
String* name = String::createWithFormat("%s%d.png", iName, index);
frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(name->getCString());
frameVec.pushBack(frame); //将生成的帧添加到Vector中
}
Animation* animation = Animation::createWithSpriteFrames(frameVec);
animation->setLoops(iloops);
animation->setDelayPerUnit(delay);
<span style="white-space:pre"> </span>aniamtion->setRestoreOriginalFrame(true); //播放完成之后回到初始帧
Animate* animate = Animate::create(animation);
return animate;
}
三种方法中,还是第一种比较方便,不需要知道图片的数量。
后两种形式差不多,只是在存储帧的方法上略有不同。