How to add infinite backgrounds in Cocos2D, iphone?

By | December 24, 2010

You often may need scrolling backgrounds in your game or any other application.
The following code helps you to add continuous backgrounds.
Each sprite is added to the right of the current sprite which make them continuos.

//Add more stripes, flip them, and position them next to their neighbour stripe.
for (int i = 0; i < numStripes; i++)
{
	NSString* frameName = [NSString stringWithFormat:@"bg%i.png", i];
	CCSprite* sprite = [CCSprite spriteWithSpriteFrameName:frameName];

	// Position the new sprite one screen width to the right.....
	sprite.position = CGPointMake(screenSize.width + screenSize.width / 2 screenSize.height / 2);

	// Flip the sprite so that it aligns perfectly with its neighbour.....
	sprite.flipX = YES;

	// Add the sprite using the same tag offset by numStripes.....
	[spriteBatch addChild:sprite z:i tag:i + numStripes];
}

Leave a Reply

Your email address will not be published. Required fields are marked *