How to clone a Sprite from another

Hi,
i would like to know the best way to create a second sprite by just copying the first .
something like sprite2 = Sprite::create(sprite1); or sprite2 = sprite1->clone(); .

Any suggestions would be greatly appreciated.

Best regards.

I’ve recently done this myself. As the Sprite itself doesn’t implement a clone() method, you’ll have to implement it yourself (not necessarily as part of Sprite, you could have a global SpiteClone()).
As to what you copy, it depends on what exactly you’re interested in from the original sprite. I’d assume Texture is a given, and in my case I wanted rotation and scale too:

Sprite *clonedSprite = Sprite::createWithTexture(originalSprite->getTexture());
clonedSprite->setScale(originalSprite->getScaleX(), originalSprite->getScaleY());
clonedSprite->setRotation(originalSprite->getRotation());

Then do whatever you want with the cloneSprite.
You might also be interested in contentSize if you manually modify it, but if you don’t then creating with the same texture will set it to the same value in the new clone.

You might also be interested in other elements of the Sprite, such as children, listeners, components, etc.all of which you’d have to clone separately.

1 Like

Don’t forget any other data that might need to be copied such as tags, user defined data, etc. This can also become complicated if the sprite has children, so be very careful.

2 Likes

@Javy @jPinhao, Thank you.

Dear all,

To precise the jPinhao answer, I think that to make it work in all cases, that’s the sprite frame which must be copied, and not the texture :

Sprite* zoomedImage = Sprite::createWithSpriteFrame(pSprite->getSpriteFrame());

In case of Sprite created from a big sprite sheet, the texture contains the entire sheet while the frame contains only the part of the sheet used by the sprite ! :wink:

2 Likes