1
votes

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];
}
2
I would use CCSpriteBatchNode if all the sprites will have the same texture. Look at stackoverflow.com/questions/4927516/… - Jonathan King

2 Answers

4
votes

Actually, the CCSprite constructor looks up in cocos' texture cache, and if the cache already contains the texture, il reuses its texture. So you could simplify further by removing the *texture (which i believe is leaked here), and just use do this:

- (void)displayLifes:(int) nrOfLifes
{
    CGPoint position = ccp(90, 450);    

    for(int i = 1 ; i <= nrOfLifes ; i++)
    {
        CCSprite *life = [CCSprite spriteWithFile:@"life.png"];
        [life setPosition:position];
        [life setScale:0.5f];
        [self addChild:life z:5 tag:i];
         position.x += 15;
    }
}
2
votes

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!