iphonexcodecocos2d-iphoneccsprite

How to get the height and width of a CCSprite made up of sub sprites (Cocos2D)


I have something like this

CCSprite *rootSprite = [CCSprite node];
CCSprite *subSpriteOne = [CCSprite spriteWithFile:@"sprite1.png"];
subSpriteOne.position = ccp(10, 10);
[rootSprite addChild:subSpriteOne];
CCSprite *subSpriteTwo = [CCSprite spriteWithFile:@"sprite2.png"];
subSpriteTwo.position = ccp(100, 100);
[rootSprite addChild:subSpriteTwo];

My problem is that the properties rootSprite.size.height and rootSprite.size.width both return 0.0. Is there any way to make the rootSprite return the actual height and width that the node and its sub nodes are taking up on the screen?


Solution

  • You can do it but you'll have to do the calculations yourself. The standard content size property returns the size of the sprite's texture, but since your sprite doesn't have a texture it has a size of 0.

    So what do you do? Well you will have to write your own method that looks at each children of the sprite and considers their size and offsets from the root sprite's position. It may get a little complicated if you don't know how many sprites you will be adding to the root, but you can write a general case.

    -(CGSize) getSizeOfRootSprite:(CCSprite*)root
    {
        float minX = 0;
        float minY = 0;
        float maxX = root->getContentSize().width;
        float maxY = root->getContentSize().height;
        for (CCSprite *child in root.children)
        {
            CGPoint pos = child.position;
            CGSize size = child.contentSize;
            if (pos.x - size.width/2 < minX) minX = pos.x - size.width/2;
            if (pos.y - size.height/2 < minY) minY = pos.y - size.height/2;
            if (pos.x + size.width/2 > maxX) maxX = pos.x + size.width/2;
            if (pos.y + size.height/2 > maxY) maxY = posY + size.height/2;
        }
        return CGSizeMake(maxX - minX, maxY - minY);
    }
    

    In other words, you have to examine each child sprite and check how its size contributes to the overall size of the root sprite.