How to change a sprite after adding its as a child?

I need to change a sprite after adding its as a child. For example, I have two sprites:

CCSprite *firstSprite;
CCSprite *secondSprite;

firstSprite = new CCSprite();
firstSprite->initWithFile( "Icon-72.png" );
firstSprite->setPosition( cocos2d::CCPoint( 300, 300 ) );
firstSprite->setAnchorPoint( cocos2d::CCPoint( 0, 0 ) );

secondSprite = new CCSprite();
secondSprite->initWithFile( "CloseNormal.png" );
secondSprite->setPosition( cocos2d::CCPoint( 400, 250 ) );
secondSprite->setAnchorPoint( cocos2d::CCPoint( 0, 0 ) );

addChild( firstSprite );
addChild( secondSprite );

firstSprite = secondSprite;

At the last line: “firstSprite = secondSprite;”, I tried to “copy” the secondSprite to the firstSprite but nothing changes. Cocos2d-x shows me two different sprites again. What I do wrong?

*CCSprite::setDisplayFrame()*

firstSprite -> setDisplayFrame( secondSprite -> displayFrame() );

Not sure if it works, though. Not on a machine right now.

I am sure that one, “firstSprite = secondSprite” will not work, because that just copies the pointer.

Will this one work? :
* firstSprite = *secondSprite;

Lance Gray wrote:

*CCSprite::setDisplayFrame()*
Not sure if it works, though. Not on a machine right now.

That works! :slight_smile:

sijie shuai wrote:

Will this one work? :
* firstSprite = *secondSprite;

That’s not work :slight_smile: The firstSprite just disappears from the screen :slight_smile:

Perhaps you should read a bit about pointers in C++ to have a better understanding of how things works.

That said, there are several things you may want to do :

  • change the texture. Lance’s code do just that. I would have used the getTexture/setTexture methods, not sure it works either.
  • copy all the sprite properties. In that case, you have to either copy one by one every property, or use the copy() method, but I’m not sure that method is properly implemented for that kind of usage.