Since the Cocos2d-X 2.0 rc2 a lot of the initialisation has changed so this code works in Cocos2d-X 2.0.
First create a sprite sheet so we can load it in.
Once you have created the Sprite Sheet you will end up with a image file and plist.
mySprites.png
mySprites.plist
I like to name my sprites like this:
jumpAnimation_00
jumpAnimation_01
jumpAnimation_02
jumpAnimation_03
jumpAnimation_04
jumpAnimation_05
walkAnimations_00
walkAnimations_01
walkAnimations_02
walkAnimations_03
walkAnimations_04
walkAnimations_05
It makes creating the animations easier. My code below is depended on the above naming convention.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
void creatAnimation() { //load plist and it will load in the png with the same name //the frames will be stored in the CCSpriteFrameCache so you can get the frames at you leisure CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("mySprites.plist"); //the frames will be gathered in the animation object CCAnimation* jumpAnim = animationName("jumpAnimations"); jumpAnim->setDelayPerUnit(0.2); //create sprite first frame from animation first frame CCSprite *jumpSprite = CCSprite::create((CCSpriteFrame*) jumpAnim->getFrames()->objectAtIndex(0)); CCAction *jumpAct = CCRepeatForever::create(jumpAnim); jumpSprite->runAction(jumpAct); this->addChild(spriteAnim); } //this method loops through the CCSpriteFrameCache to get the CCAnimation *animationName(char const *name) { //creates a temp animation object CCAnimation* holderAnim = CCAnimation::create(); //variables used for the loop string fName; string tName = name; CCSpriteFrame* pFrame; int frameCount = 1; //loops till it can't find any more frames do { //adds the underscore and a zero if the image is less than 10 fName = (frameCount < 10) ? tName + "_0" : tName + "_"; //adds the image number---Utils::num2str() converts an integer to a string fName = fName + Utils::num2str(frameCount); frameCount++; //tries to get the frame //tries to get the frame pFrame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(fName.c_str()); //adds the frame to the animation holder if (pFrame) holderAnim->addSpriteFrame(pFrame); //continues too loop till the next frame is null } while(pFrame != NULL); return holderAnim; } |