In cocos2d-x, how can I change the png that is used by a sprite?
The following works, however it seems a bit longwinded and I was wondering if there is an alternative that prevents me from having to call new
?
// create sprite with original png
m_pSpr = CCSprite::create( "1.png" );
m_pSpr->setPosition( ccp( 100, 100 ) );
this->addChild( m_pSpr );
// now change the png that is used by the sprite
// new image from png file
CCImage* img = new CCImage();
img->initWithImageFile( "2.png", CCImage::kFmtPng );
// new texture from image
CCTexture2D* tex = new CCTexture2D();
tex->initWithImage( img );
// finally change texture of sprite
m_pSpr->setTexture( tex );
Pack your sprites into a spritesheet, then use CCSprite's setDisplayFrame().
// make sure the spritesheet is cached
auto cacher = CCSpriteFrameCache::sharedSpriteFrameCache();
cacher->addSpriteFramesWithFile("Spritesheet.plist");
// create the sprite
m_pSpr = CCSprite::create( "1.png" );
// set it's display frame to 2.png
CCSpriteFrame* frame = cacher->spriteFrameByName("2.png");
if( frame)
m_pSpr->setDisplayFrame(frame);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With