转载请注明出处:http://blog.csdn.net/cwn0812
cocos2d-x播放序列动画分为两种方法,
1为直接读序列图片,然后runAction,;
2为读取plist文件读取图片,在runAction
我感觉两种其实都是一种方式,先读图片资源,把图片资源放到frame中,并把frame添加到CCArray中,在创建action ,然后runAction
1:
//创建一个数组,存储CCSpriteFrame
CCArray* frames = CCArray::create();
//for循环读取图片资源
for (int i=1;i<=7;i++)
{
//定义char型str
char str[100] = {0};
//存储字符串,并赋值str,
//在resource目录下图片的名称:test1,test2.....test7;
sprintf(str,"test%d.png",i);//sprintf这个函数很重要
//用str来创建CCSpriteFrme,并定义CCRect中对应图片的位置和宽度高度
CCSpriteFrame* sprite = CCSpriteFrame::create(str,CCRectMake(0,0,100,100));
//添加CCSpriteFrme
frames->addObject(sprite);
}
//创建第一帧
CCSprite* sprite = CCSprite::create("test1.png");
//设置位置,要与上面的CCRect对牢。
sprite->setPosition(ccp(size.height/2,size.width/2-100));
this->addChild(sprite);
//用数组frames创建CCAnimation
CCAnimation* action = CCAnimation::createWithSpriteFrames(frames,0.5f);
//运行动画
sprite->runAction(CCAnimate::create(action));
//运行循环动画
//sprite->runAction(CCRepeatForever::create(CCAnimate::create(action)));
2:
//你用TexturePacker生成的plist有两个文件,一个是以.plist为结尾的,一个是以.png结尾的。
//定义存储plist的str1
char str1[100] = {0};
//定义存储png的str2
char str2[100] = {0};
//创建一个cache
CCSpriteFrameCache *cache = CCSpriteFrameCache::sharedSpriteFrameCache();
//读取plist文件存为str1,例子为test.plist
sprintf(str1, "%s.plist", "test");
//读取plist文件存为str2,例子为test.png
sprintf(str2, "%s.%s", "test","png");
//cache添加解析str1,str2
cache->addSpriteFramesWithFile(str1,str2);
//创建数组animFrames
CCArray* animFrames = CCArray::create();
//设置开始帧数
int beginIndex =1;
//设置结束帧数
int endIndex = 7;
int i = beginIndex;
//开始循环
do {
//判断是否结束
if (endIndex>1&&(i-1)==endIndex)
{
break;
}
//读取plist中的key值
sprintf(str2, "%s%d.png", "test",i);
//创建frame
CCSpriteFrame *frame = cache->spriteFrameByName(str2);
if (frame) {
//不为空,添加到数组里
animFrames->addObject(frame);
}else {
break;
}
} while (++i);
//下面也上面的说明一样
CCAnimation *animation = CCAnimation::createWithSpriteFrames(animFrames, 1.0f);
//cache中删除spriteFrames
cache->removeSpriteFramesFromFile(str1);
//动画结束后是否返回初始帧
//animation->setRestoreOriginalFrame(true);
//一些函数可以到源码看意思
//创建精灵
sprintf(str2, "%s%d.png", "test",beginIndex);
CCSprite* sprite = (CCSprite*)cache->spriteFrameByName(str2);
sprite->setPosition(ccp(size.width/2,size.height/2-100));
this->addChild(sprite);
//runAction
sprite->runAction(CCAnimate::create(animation));
差不多就是以上形式,希望有所帮助