#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);