Adding .plist Animations to Your Project in Cocos2d-X

I had a really hard time finding documentation on how to implement a .plist-based animation in Cocos2d-X. There were a lot of incomplete code snippets online, but no working example until I found this video on YouTube by Tim Richardson. His tutorial is excellent and the only problem I found, was that because it is a video, the code itself is hard to read. So,below is our working code that is easy to replicate. Feel free to use and share and don’t forget to thank Tim!

First create a CCSpriteFrameCache to hold the frames of your animation and add the frames from your animation .plist.

CCSpriteFrameCache* framecache = CCSpriteFrameCache::sharedSpriteFrameCache();
framecache->addSpriteFramesWithFile("LoadingBubble.plist");

Second, create a batch node to hold the sprite sheet where your frames live and add it to the batch node.

CCSpriteBatchNode *batch = CCSpriteBatchNode::create("Level01_Dan_Loading.png");
CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("Level01_Dan_Loading.plist");
this->addChild(batch, 1);

Next, create an array to hold the frames of your animation and add it to the array. The frame names will be in your .plist. Your .plist will also tell you how many frames are in your animation. This animation example only has two frames, so i = 1 is the first frame and i <= 2 is the last frame. It is very important to name your frames the same, with only a different number on the end, so the array can easily increment them.

CCArray* bubbleframes = new CCArray();
for (int i = 1; i <= 2; i++) {
        CCString* filename = CCString::createWithFormat("LoadingBubble%d", i);
        CCSpriteFrame* frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(filename->getCString());
        bubbleframes->addObject(frame);
}

Now, we're going to define how long each frame of the animation is displayed. The number is in tenths of a second.

        
CCAnimation* bubbleAnim = CCAnimation::createWithSpriteFrames(bubbleframes, 0.3);

Almost done... Now we're going to assign the animation to a CCSprite, so we can scale and position it.

 
CCSprite* bubbleFrame = CCSprite::createWithSpriteFrameName("LoadingBubble1");
CCSize bubFrame = CCDirector::sharedDirector()->getWinSize();
bubbleFrame->setPosition(ccp(bubFrame.width / 2, bubFrame.height-120));
bubbleFrame->setScale(2.0f);

Finally, since this is a looping animation, we're going to set it to repeat forever in a CCAction, run the animation, and add it to our batch node on the z-index we define.

      
CCAction* action = CCRepeatForever::create(CCAnimate::create(bubbleAnim));
bubbleFrame->runAction(action);
this->addChild(bubbleFrame,3);

And there you have it, a simple way to add .plist-based animations to your project in Cocos2d-X.