#Cocos2d-x-基本概念-Animationsnode
###帧动画数组
你能够经过一系列的图片来建立一个童话,以下动画
CCAnimation *animation = CCAnimation:create(); //load image file from local system to CCSpriteFrame, then add into CCAnimation for (int i = 0; i < 15; ++i) { char szImageFileName[128] = {0}; sprintf(szImageFileName, "Images/grossini_dance_%02d.png", i); animation->addSpriteFrameWithFilename(szImageFileName); } animation->setDelayPerUnit(2.8f / 14.0f);// This animation contains 14 frames, will continuous 2.8 seconds. animation->setRestoreOriginalFrame(true);// Return to the 1st frame after the 14th frame is played. CCAnimate *action = CCAnimate::create(animation); sprite->runAction(action);
注意CCAnimation是由SpriteFrame的数组、每帧之间的间隔时间,真个动画的长度等组成的,它是一组数据,相比之下,CCAnimate是一个Action,它是根据CCAnimation构建的this
###SpriteSheet动画code
上一种方法实际上不常在2d游戏中用到,咱们在2d游戏中常常用到一种叫spritesheet的方法载入图像xml
下图就是典型的spritesheet,它由一个动画的不一样帧组成,或者他能够保存在游戏中一个场景所须要的全部场景接口
在opengles1.1中,spritesheet有如下几个好处:游戏
###从png和plist中建立动画图片
自从运用了opengl2.0后,CCSpriteSheet逐渐被CCSpriteBatchNode取代内存
CCSpriteBatchNode实际上包含了全部SpriteFrame所须要的图片素材。你必须把它add到一个scene上,即便它自己什么也不会画,它只是因为它是opengl的渲染管线的一部分才添加到scene上的
CCSpriteBatchNode* spritebatch = CCSpriteBatchNode::create("animations/grossini.png");
而后,你须要用CCSpriteFrameCache的单件来获得plist文件,plist中记载了spritesheet中每一帧的大小和名字等信息
CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache(); cache->addSpriteFramesWithFile("animations/grossini.plist");
一旦你的png和plist文件都载入好了,你就可使用createWithSpriteFrameName方法来建立Sprite了,
m_pSprite1 = CCSprite::createWithSpriteFrameName("grossini_dance_01.png"); spritebatch->child(m_pSprite1) addChild(spritebatch)
createWithSpriteFrameName从plist中找到对应桢并对png进行剪切,获取相应的图片
如今咱们经过CCArray来建立一个动画跑在精灵m_pSprite上
CCArray* animFrames = CCArray::createWithCapacity(15); char str[100] = {0}; for(int i = 1; i < 15; i++) { sprintf(str, "grossini_dance_%02d.png", i); CCSpriteFrame* frame = cache->spriteFrameByName( str ); animFrames->addObject(frame); }
###File Animation
CCAnimationCache可以加载一个描述一个batchnode的xml或者plist,接口以下
CCAnimationCache *cache = CCAnimationCache::sharedAnimationCache(); // "caches" are always singletons in cocos2d cache->addAnimationsWithFile("animations/animations-2.plist"); CCAnimation animation = cache->animationByName("dance_1"); // I apologize for this method name, it should be getAnimationByName(..) in future versions CCAnimate animate = CCAnimate::create(animation); // Don't confused between CCAnimation and CCAnimate :) sprite->runAction(animate);