views:

714

answers:

1

Hi all,

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.

+1  A: 

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.

GamingHorror
Thanks buddy. for your help.
iPhone Fun
Bus is it possible to use array and for loop to change the background? As will make code some what complecated.
iPhone Fun
You could load all backgrounds up front and put them into an array, and keep a counter that tells you which is the current image. During replaceBackground you increase the counter and use that to load the appropriate image on screen. That would work too. No for loop needed.
GamingHorror