Search code examples
cocos2d-iphoneparallaxccspriteinitializer

Issues with creating a CCParallaxNode in cocos2d?


I'm using a CCParallaxNode for a scrolling background in my GameLayer and I'm getting a bunch of errors and I can't figure out why.

"Initializer element is not a compile-time constant" and also "Unk

@implementation Background

// Load the sprites for each parallax layer, from background to foreground.
CCSprite* para1 = [CCSprite spriteWithFile:@"color.png"];
CCSprite* para2= [CCSprite spriteWithFile:@"ship-hd.png"];
CCSprite* para3 = [CCSprite spriteWithFile:@"twit.png"];
CCSprite* para4 = [CCSprite spriteWithFile:@"Start.png"];

// Set the correct offsets depending on the screen and image sizes.
para1.anchorPoint = CGPointMake(0, 1);
para2.anchorPoint = CGPointMake(0, 1);
para3.anchorPoint = CGPointMake(0, 0.6f);
para4.anchorPoint = CGPointMake(0, 0);

CGPoint topOffset = CGPointMake(0, screenSize.height);
CGPoint midOffset = CGPointMake(0, screenSize.height / 2);
CGPoint downOffset = CGPointZero;

// Create a parallax node and add the sprites to it.
CCParallaxNode* paraNode = [CCParallaxNode node];
[paraNode addChild:para1 z:1 parallaxRatio:CGPointMake(0.5f, 0) ositionOffset:topOffset];

[paraNode addChild:para2 z:2 parallaxRatio:CGPointMake(1, 0) positionOffset:topOffset];

[paraNode addChild:para3 z:4 parallaxRatio:CGPointMake(2, 0) positionOffset:midOffset];

[paraNode addChild:para4 z:3 parallaxRatio:CGPointMake(3, 0) positionOffset:downOffset];

[self addChild:paraNode z:0 tag:ParallaxSceneTagParallaxNode];

                   // Move the parallax node to show the parallaxing effect.
                   CCMoveBy* move1 = [CCMoveBy actionWithDuration:5 position:CGPointMake(−160, 0)];
                   CCMoveBy* move2 = [CCMoveBy actionWithDuration:15 position:CGPointMake(160, 0)];
                   CCSequence* sequence = [CCSequence actions:move1, move2, nil];

                   CCRepeatForever* repeat = [CCRepeatForever actionWithAction:sequence];
                   [paraNode runAction:repeat];

@end

Solution

  • You need to enclose your code in an -(id)init method, like this:

    @implementation Background
    
    - (id)init
    {
        if (self = [super init]) {
            // Load the sprites for each parallax layer, from background to foreground.
            CCSprite* para1 = [CCSprite spriteWithFile:@"color.png"];
            // ... the rest of your code ... //
        }
        return self;
    }
    
    @end