Search code examples
iphoneioscocos2d-iphoneparticlescclayer

Cocos2d. One instance of CCLayer with particles for a lot of scenes?


I want to create a starry sky for some scenes. The main problem is it needs some time to fill all the screen with particles. Someone advices me to create the whole sky at the beginning and save it between its calls. I tried something like this:

@implementation StarrySky

static StarrySky *_starrySky;

- (id)init
{
    if ((self = [super init])) {
        NSArray *starsArray = [NSArray arrayWithObjects:@"Stars1.plist", @"Stars2.plist", @"Stars3.plist", nil];
        for(NSString *stars in starsArray) {        
            CCParticleSystemQuad *starsEffect = [CCParticleSystemQuad particleWithFile:stars];        
            [self addChild:starsEffect z:-2];
        }
    }
    return self;
}

+ (StarrySky *)sharedStarrySky
{
    if (!_starrySky) {
        _starrySky = [[StarrySky alloc] init];
    }
    return _starrySky;
}

- (void)dealloc
{
    _starrySky = nil;
    [super dealloc];
}

@end

But the particles stop moving.


Solution

  • One solution that ought to work is to create the star particle system and add it to your first scene (ie main menu). Set it to invisible or move it way off the screen or behind the background image (lowest z-order) so it can create some stars without actually showing any stars in the menu.

    Now when you switch to your actual game scene, you alloc/init the game scene and then remove the star particle system from the currently running scene and add it to the game scene. Basically you're moving it from one scene to another.

    Now you can call replaceScene with the game scene which now contains the already active star particle system.