Search code examples
iphoneobjective-ccocos2d-iphoneccsprite

Creating multiple identical CCSprites


Is there a clean and efficient way to create an arbitrary number of identical CCSprites?

I really just need a tag to reference them for later removal.

For example in my game I am displaying the number of lives in a HUD:

- (void)displayOneLife
{
    CGPoint positionOne = ccp(90, 450);

    CCSprite *life1 = [CCSprite spriteWithFile:@"life.png"];
    [life1 setPosition:positionOne];
    [life1 setScale:0.5f];
    [self addChild:life1 z:5 tag:1];
}

- (void)displayTwoLives
{
    CGPoint positionOne = ccp(90, 450);
    CGPoint positionTwo = ccp(105, 450);

    CCSprite *life1 = [CCSprite spriteWithFile:@"life.png"];
    CCSprite *life2 = [CCSprite spriteWithFile:@"life.png"];

    [life1 setScale:0.5f];
    [life2 setScale:0.5f];

    [life1 setPosition:positionOne];
    [life2 setPosition:positionTwo];

    [self addChild:life1 z:5 tag:1];
    [self addChild:life2 z:5 tag:2];
}

- (void)displayThreeLives
{
    CGPoint positionOne = ccp(90, 450);
    CGPoint positionTwo = ccp(105, 450);
    CGPoint positionThree = ccp(120, 450);

    CCSprite *life1 = [CCSprite spriteWithFile:@"life.png"];
    CCSprite *life2 = [CCSprite spriteWithFile:@"life.png"];
    CCSprite *life3 = [CCSprite spriteWithFile:@"life.png"];

    [life1 setPosition:positionOne];
    [life2 setPosition:positionTwo];
    [life3 setPosition:positionThree];

    [life1 setScale:0.5f];
    [life2 setScale:0.5f];
    [life3 setScale:0.5f];

    [self addChild:life1 z:5 tag:1];
    [self addChild:life2 z:5 tag:2];
    [self addChild:life3 z:5 tag:3];
}

Solution

  • Create a CCTexture2D using your image and then init all of the sprites using that texture. This way you only load the image once.

    Hope this helps.

    EDIT:

    Also , you can add them dynamically. Like this:

    - (void)displayLifes:(int) nrOfLifes
    {
        CGPoint position = ccp(90, 450);
        CCTexture2D *texture = [[[CCTexture2D alloc] initWithImage:[UIImage imageNamed:@"life.png"]]autorelease];
    
        for(int i = 1 ; i <= nrOfLifes ; i++)
        {
             CCSprite *life = [CCSprite spriteWithTexture:texture];
             [life setPosition:position];
             [life setScale:0.5f];
             [self addChild:life z:5 tag:i];
    
             position.x += 15;
        }
    }
    

    Cheers!