Change the background image in cocos2d

V.V picture V.V · May 25, 2010 · Viewed 12.3k times · Source

I am making a game using cocos2d. in that I want to change the background after each second of time. I don't know how to do this in cocos2d. I am having 15 different images and one by one each image will be shown, i.e. after1 second next image will appear.

I am new to cocos2d so, If any one can help me???

thank you in advance to all.

Answer

LearnCocos2D picture LearnCocos2D · May 25, 2010

I assume by background you mean an image with the full 320x480 resolution.

You will have to create and add a CCSprite:

CCSprite* background = [CCSprite spriteWithFile:@"bg1.png"];
background.tag = 1;
background.anchorPoint = CGPointMake(0, 0);
[self addChild:background];

To schedule replacement use a scheduler:

[self schedule:@selector(replaceBackground:) interval:1.0f];

When replacing the background, don't forget to remove the old background:

-(void) replaceBackground:(ccTime)delta
{
    // add new background here...

    [self removeChildByTag:1];
}

Tag should increase with each image of course.

One word of caution: loading a 320x480 (which will be a 512x512 texture in memory, using 1 MB of memory unless 16-bit or PVR compressed) from file will cause a noticeable lag. If you're doing an action game you will have to preload the background images. This will leave you with little memory to go with for the rest of the game (15 images x 1 MB = 15 MB of maybe 25 MB available memory).

PS: more Q&A is available in the cocos2d forum: http://www.cocos2d-iphone.org/forum and i also keep adding FAQ answers to my http://www.learn-cocos2d.com website.