[done] How to reuse CCSprite?

Hi,
I have a sprite with several other added sprites (as children).
This ‘parent’ sprite is used at CCMenuItem definition as normal and selected images…

It’s a waste of time call twice the function to create the ‘parent’ sprite, when work is already done.
No try of copy() or CCCopying() methods have worked for me, nor node()…
Any ideas?

Thanks,
Jordi

Well…
I finally find out a way to do it… any improvements will be more than wellcome :wink:

The point is that CCSprite::spriteWithTexture only gets the ‘root’ image, so all that have to be done is go through its childs recursively, getting all their properties:

CCSprite* GameScene::duplicateSprite(cocos2d::CCSprite *sprite) {
    CCSprite* pRet = CCSprite::spriteWithTexture(sprite->getTexture());
    if (sprite->getChildrenCount() > 0) {
        for (int child = 0; child < sprite->getChildrenCount(); child++) {
            CCSprite* spriteChild = (CCSprite*)sprite->getChildren()->objectAtIndex(child);
            CCSprite* clone = duplicateSprite((CCSprite*)spriteChild);
            clone->boundingBox() = spriteChild->boundingBox();
            clone->setContentSize(spriteChild->getContentSize());
            clone->setPosition(spriteChild->getPosition());
            clone->setAnchorPoint(spriteChild->getAnchorPoint());
            pRet->addChild(clone, spriteChild->getZOrder(), spriteChild->getTag());
        }
    }   

    return pRet;
}

Hope it helps,
Jordi :slight_smile:

thanks for sharing, great post

mmm I just noticed it does not works when you try to clone a texture that comes from a rotated sprite inside an sprite sheet (made with texture packer for instance). It’s strange since I have even tried to establish the rotation property.

Hi!
I haven’t tried this with sprite sheets… as you mention…
but I’ve noticed another point: when you apply opacity action (at the moment I’ve made no further tests) to a nested sprite, action doesn’t propagate to its childs.

In my case there is only a CCLabelTTF inside CCSprite, and while sprite fade out label isn’t affected.
Seems to be the way action works; perhaps happens the “same” in your case.

Regards,
Jordi

hi sir, do you have a code like this in v3???