The following operations are used to implement cyclic scrolling of background images:
There are two main background images that rotate cyclically: the width of the two selected background images is 1024, so # define BGIMG_WIDTH 1024 is defined.
The Code is as follows:
Declare two background image genie in the header file of HelloWorld. h.
#import "cocos2d.h"// HelloWorldLayer@interface HelloWorldLayer : CCLayer { CCSprite *bagSprite1; CCSprite *bagSprite2;}
Some Code implemented in the. m file:
# Import "HelloWorldLayer. h "# import" AppDelegate. h "# pragma mark-HelloWorldLayer # define BGIMG_WIDTH 1024 // HelloWorldLayer implementation @ implementation HelloWorldLayer-(id) init {if (self = [super init]) {CGSize winSize = [CCDirector shareddire]. winSize; bagSprite1 = [CCSprite spriteWithFile: @ "bag1.jpg"]; bagSprite2 = [CCSprite spriteWithFile: @ "bag2.jpg"]; Weight = ccp ); [bagSprite1 setScaleY: winSize. height/bagSprite1.textureRect. size. height]; // modify the height of the background image [bagSprite2 setScaleY: winSize. height/bagSprite2.textureRect. size. height]; bagSprite1.position = ccp (0, 0); bagSprite2.position = ccp (-BGIMG_WIDTH, 0 ); // the start position of the second image is on the left of the first image. // Add the genie [self addChild: bagSprite1 z: 1]; [self addChild: bagSprite2 z: 1]; CCMoveBy * Signature = [CCMoveBy actionWithDuration: 6.0f position: ccp (BGIMG_WIDTH, 0)]; CCMoveBy * Signature = [CCMoveBy actionWithDuration: 6.0f position: ccp (BGIMG_WIDTH, 0)]; CCCallBlock * bagSprite1Finish = [CCCallBlock actionWithBlock: ^ (void) {[self defined: bagSprite1] ;}]; CCCallBlock * bagSprite2Finish = [CCCallBlock actionWithBlock: ^ (void) {[self defined: bagSprite2] ;}]; [bagSprite1 runAction: [CCSequence actions: complete, bagSprite1Finish, nil]; [bagSprite2 runAction: [CCSequence actions: complete, bagSprite2Finish, nil];} return self;}-(void) actionFinishedWithSprite :( CCSprite *) theSprite {if (theSprite. position. x = 0) {CCMoveBy * bagSpriteMoveBy = [CCMoveBy actionWithDuration: 6.0f position: ccp (BGIMG_WIDTH, 0)]; CCCallBlock * bagSpriteFinish = [CCCallBlock actionWithBlock: ^ (void) {[self actionFinishedWithSprite: theSprite];}]; [theSprite runAction: [CCSequence actions: bagSpriteMoveBy, bagSpriteFinish, nil];} else if (theSprite. position. x = BGIMG_WIDTH) {[theSprite setPosition: ccp (-BGIMG_WIDTH, 0)]; CCMoveBy * bagSpriteMoveBy = [CCMoveBy actionWithDuration: 6.0f position: ccp (BGIMG_WIDTH, 0)]; CCCallBlock * bagSpriteFinish = [CCCallBlock actionWithBlock: ^ (void) {[self failed: theSprite] ;}]; [theSprite runAction: [CCSequence actions: bagSpriteMoveBy, bagSpriteFinish, nil] ;}}@ end
Running result: