感谢hxy060799的分享!
在子龙山人翻译的Cocos2d太空射击游戏里面有提到关于背景图片的循环滚动,但是这种方式是通过Category来实现的,而且我cocos2d 2.X用这个方法会编译出一大堆莫名其妙的错误,所以自己写了一个背景循环滚动的代码。
效果这样,这张图片不断的滚动

//.h
#import "cocos2d.h"
@interface HelloWorldLayer : CCLayer
{
CCSprite *pic1;
CCSprite *pic2;
}
@property(retain,nonatomic)CCSprite *pic1;
@property(retain,nonatomic)CCSprite *pic2;
+(CCScene *) scene;
@end
//.m中的重要方法
-(void)actionFinishedWithSprite:(CCSprite*)theSprite{
if(theSprite.position.y==0){
CCMoveBy *picMoveBy=[CCMoveBy actionWithDuration:1.0f position:ccp(0,-320)];
CCCallBlock *picFinish=[CCCallBlock actionWithBlock:^(void){[self actionFinishedWithSprite:theSprite];}];
[theSprite runAction:[CCSequence actions:picMoveBy,picFinish,nil]];
}else if(theSprite.position.y==-320){
[theSprite setPosition:ccp(0,320)];
CCMoveBy *picMoveBy=[CCMoveBy actionWithDuration:1.0f position:ccp(0,-320)];
CCCallBlock *picFinish=[CCCallBlock actionWithBlock:^(void){[self actionFinishedWithSprite:theSprite];}];
[theSprite runAction:[CCSequence actions:picMoveBy,picFinish,nil]];
}
}
-(id) init
{
if(self=[super init]) {
pic1=[CCSprite spriteWithFile:@"Default_.png"];
pic2=[CCSprite spriteWithFile:@"Default_.png"];
pic1.anchorPoint=ccp(0,0);
pic2.anchorPoint=ccp(0,0);
pic1.position=ccp(0,0);
pic2.position=ccp(0,320);
[self addChild:pic1 z:1];
[self addChild:pic2 z:1];
CCMoveBy *pic1MoveBy=[CCMoveBy actionWithDuration:1.0f position:ccp(0,-320)];
CCMoveBy *pic2MoveBy=[CCMoveBy actionWithDuration:1.0f position:ccp(0,-320)];
CCCallBlock *pic1Finish=[CCCallBlock actionWithBlock:^(void){[self actionFinishedWithSprite:pic1];}];
CCCallBlock *pic2Finish=[CCCallBlock actionWithBlock:^(void){[self actionFinishedWithSprite:pic2];}];
[pic1 runAction:[CCSequence actions:pic1MoveBy,pic1Finish,nil]];
[pic2 runAction:[CCSequence actions:pic2MoveBy,pic2Finish,nil]];
}
return self;
}

比较简单我就不加以解释了,原理大家直接看下面的那个图就可以弄懂。

[dl href=”http://vdisk.weibo.com/s/8U2Is”]点此下载背景图片循环滚动的代码[/dl]