Change the background image in cocos2d

12,483

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.

Share:
12,483
V.V
Author by

V.V

I am an iPhone/iPad application and Game developer. Also working in c# applications and Web development.

Updated on June 02, 2022

Comments

  • V.V
    V.V almost 2 years

    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.

    • V.V
      V.V almost 14 years
      Is it possible to use timer for the same? as we are using in simple iphone animation? here is some information if any one can help me,cocos2d-iphone.org/wiki/doku.php/prog_guide:animation This is for sprite, but I am not able to use it for images.
  • V.V
    V.V almost 14 years
    Bus is it possible to use array and for loop to change the background? As will make code some what complecated.
  • LearnCocos2D
    LearnCocos2D almost 14 years
    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.