您的位置:首页 > 移动开发 > Cocos引擎

cocos2dx中创建动画的三种方法

2014-11-12 22:09 323 查看
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中提取图片帧来创建动画打包的步骤.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: