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

14,086

Solution 1

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

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

Solution 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");

Solution 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);
}
Share:
14,086
azelez
Author by

azelez

I am stating to make simple teaching multi-player apps.

Updated on July 19, 2022

Comments

  • azelez
    azelez almost 2 years

    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.

  • azelez
    azelez almost 12 years
    Yeah it does. Its more elegant than the way I used to fix my problem. Thanks.
  • Nikhil Aneja
    Nikhil Aneja almost 12 years
    accept the answer and close it else people will keep posting answers.. :)
  • Vladimir Vovk
    Vladimir Vovk about 9 years
    For cocos2d-x 3.x: mySprite->setSpriteFrame("frame_name");