简体   繁体   中英

Cocos2d-x: How to replace sprite dynamically?

I am struggling to replace the sprite I selected to another sprite.

Here is what I've got so far:

void Object::replaceSprite(const string & resourceName)
{
    cocos2d::SpriteFrameCache * spriteFrameCache = cocos2d::SpriteFrameCache::getInstance();
    cocos2d::SpriteFrame * spriteFrame = spriteFrameCache->getSpriteFrameByName(resourceName);

    //mSprite->setTexture(spriteFrame->getTexture());
    //mSprite->setDisplayFrame(spriteFrame);
    mSprite->setSpriteFrame(resourceName);

}

As you can see, I tried different approach but none of them worked.

Also, I would like to ask if I do have to add the sprite again once I replace the frame onto the scene? What I am thinking right now is to create a new sprite every time I asked to replace it with a new one. But I do not know if there is more elegant and efficient way to do this.

Thank you!

setSpriteFrame accept a string or SpriteFrame* as argument

in your code

mSprite->setSpriteFrame(resourceName);

the argument is a string, you have no need to get frame from frameCache, but you must make sure that the frame exists in frameCache.

you can make breakpoint in the function, and check if spriteFrame is nullptr after

cocos2d::SpriteFrame * spriteFrame = spriteFrameCache->getSpriteFrameByName(resourceName);

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