简体   繁体   中英

Simple frame animation in Cocos2d V3

I am struggling to get a simple animation working in Cocos2d V3.

I initially had a simple static png used for a sprite, using this code, which works fine...

Sprite *treeStar = Sprite::create("star.png");
this->addChild(treeStar,+3);
treeStar->setPosition.... // set position is defined later

I have added the following code to try a simple animation instead of the static sprite...

auto cache = SpriteFrameCache::getInstance();
Vector<SpriteFrame*> frames = Vector<SpriteFrame*>();
frames.pushBack(cache->getSpriteFrameByName("star1.png"));
frames.pushBack(cache->getSpriteFrameByName("star2.png"));
cocos2d::Animation* anim = cocos2d::Animation::createWithSpriteFrames(frames, 0.1f, 1);
cocos2d::Animate* anim_action = cocos2d::Animate::create(anim);
Sprite *treeStar = Sprite::create("star1.png");
this->addChild(treeStar,+3);
treeStar->runAction(RepeatForever::create(anim_action));
treeStar->setPosition.... // set position is defined later

But this doesn't work and causes my app to crash.

Can anyone help advise how to get this code working, or give me another code example that will work for a simple animation?

Check this line:

Sprite *treeStar = Sprite::create("star1.png"); // crash due to image not found

The method create is used to create a sprite from an individual image not from sprite sheet. In your case, images are in a sprite sheet, change the line to:

Sprite *treeStar = Sprite::createWithSpriteFrameName("star1.png");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM