Cocos2d-x animation

775 views Asked by At

Hello I'm doing a project. I wanted to know how to animate my character. I follow the guide in cocos wiki but I can't make it possible on my code.

My character can move and walk, I want to apply an animation when he jumps.It has a onKeyPressed method. I don't know how to change the normal sprite to the movement spritesheet, I have the plist but I don't know how to load in my code.

I tried so many tutorials but I don't know how to implement them in my project.

1

There are 1 answers

1
war1oc On

I wrote a simple player movement and animation tutorial, you can find it here. You can also get the entire source code for this here.

However this tutorial does not use any spritesheet, I tried to keep it as simple as possible. To use spritesheets, you will need to do some modifications:

In your scene's "init()" method, you need to add a SpriteBatchNode object and add the plist file to the SpriteFrameCache singleton.

auto spriteBatch = SpriteBatchNode::create("sprites/sprite_sheet.png", 200);
auto spriteFrameCache = SpriteFrameCache::getInstance();
spriteFrameCache->addSpriteFramesWithFile("sprites/sprite_sheet.plist");
this->addChild(spriteBatch, kMiddleground);

Then add the player object to the SpriteBatchNode

player = Player::create();
spriteBatch->addChild(player);

Then in the player class, create the animations like this:

SpriteFrameCache* cache = SpriteFrameCache::getInstance();
Vector<SpriteFrame*> moveAnimFrames(10); // parameter = number of frames you have for this anim
char str[100] = {0};

for(int i = 0; i < 10; i++) // this 10 is again the number of frames
{
    sprintf(str, "move_%d.png", i);
    SpriteFrame* frame = cache->getSpriteFrameByName( str );
    moveAnimFrames.pushBack(frame);
}

moveAnimation = Animation::createWithSpriteFrames(moveAnimFrames, 0.011f);
moveAnimation->setLoops(-1);
moveAnimate = Animate::create(moveAnimation);
moveAnimate->retain(); // retain so you can use it again
this->runAction(moveAnimate); // run the animation

You can create different animations and change them by:

this->stopAction(moveAnimate);
this->runAction(jumpAnimate);

Hope this helps.