Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change png that is used by sprite

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 );
like image 852
Ben Avatar asked Feb 19 '23 20:02

Ben


1 Answers

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);
like image 77
Nathanael Weiss Avatar answered Feb 21 '23 11:02

Nathanael Weiss