How to swap the sprite in the CCSprite object in Cocos2d-X

自闭症网瘾萝莉.ら 提交于 2019-12-09 09:14:07

问题


I have an object that inherited from CCSprite. I want from inside this object to change the image.

How do I change the image (sprite) without creating a new CCSprite object in Cocos2d-X?

Thanks, Adrian.


回答1:


mySprite->setTexture(CCTextureCache::sharedTextureCache()->addImage("newImage.png"));

No need to alter your custom class.. Hope this helps.. :)




回答2:


Works for me:

mySprite->setDisplayFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("frame_name"));

Before you need to load you sprites in cache:

CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("sprite_atlas.plist");



回答3:


I found out, and I leave it here in case somebody gets stuck with the same problem:

Inside your object that's inherited from CCSprite object, write a function as follows

void MyObject::UpdateImage(Char * PngName)
{
   /* Create Image */
   CCImage *MyImage = new CCImage();
   MyImage->initWithImageFile( PngName ); /*the pngName is an image file in your resource folder */

   /* Create Texture from Image */
   CCTexture2D *MyTexture = new CCTexture2D();
   MyTexture->initWithImage(MyImage);

   /* Set the Texture */
   this->setTexture(MyTexture);
}



回答4:


Since "CCTextureCache::sharedTextureCache()" is now deprecated (v.3.13.1) you'd better get the texture cache from the Director:

auto texture = Director::getInstance()->getTextureCache()->addImage(filePath);

if (texture)
{
    yourSprite->setTexture(texture);
}

Source: http://www.cocos2d-x.org/wiki/Texture_Cache



来源:https://stackoverflow.com/questions/10456040/how-to-swap-the-sprite-in-the-ccsprite-object-in-cocos2d-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!