How to swap the sprite in the CCSprite object in Cocos2d-X
Asked Answered
P

4

10

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.

Pardo answered 4/5, 2012 at 20:56 Comment(0)
I
12
mySprite->setTexture(CCTextureCache::sharedTextureCache()->addImage("newImage.png"));

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

Incoming answered 5/5, 2012 at 9:45 Comment(2)
Yeah it does. Its more elegant than the way I used to fix my problem. Thanks.Pardo
accept the answer and close it else people will keep posting answers.. :)Incoming
N
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");
Nightjar answered 23/7, 2014 at 7:26 Comment(1)
For cocos2d-x 3.x: mySprite->setSpriteFrame("frame_name");Nightjar
P
1

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);
}
Pardo answered 4/5, 2012 at 21:24 Comment(0)
L
0

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

Lamarlamarck answered 21/11, 2016 at 3:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.