cocos2d(背景图片循环滚动)

背景图片循环滚动 使用action 实现的:

主要有两个背景图片交替循环滚动:我选的两个背景图片的宽度都是1024的 ,所以定义了#define BGIMG_WIDTH 1024

代码如下:

在HelloWorld.h的头文件中声明两个背景图片精灵

#import "cocos2d.h"

// HelloWorldLayer
@interface HelloWorldLayer : CCLayer 
{
    CCSprite *bagSprite1;
    CCSprite *bagSprite2;
}

在.m文件中实现的部分代码:

#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 sharedDirector].winSize;
                
        bagSprite1=[CCSprite spriteWithFile:@"bag1.jpg"];
        bagSprite2=[CCSprite spriteWithFile:@"bag2.jpg"];
        
        bagSprite1.anchorPoint=ccp(0,0);
        bagSprite2.anchorPoint=ccp(0,0);
        [bagSprite1 setScaleY:winSize.height/bagSprite1.textureRect.size.height];   //修改背景图片的高度
        [bagSprite2 setScaleY:winSize.height/bagSprite2.textureRect.size.height];
        bagSprite1.position=ccp(0,0);
        bagSprite2.position=ccp(-BGIMG_WIDTH,0);    //第二张图片的起始位置在第一张的左边
        //添加精灵
        [self addChild:bagSprite1 z:1];
        [self addChild:bagSprite2 z:1];
        
        CCMoveBy *bagSprite1MoveBy=[CCMoveBy actionWithDuration:6.0f position:ccp(BGIMG_WIDTH,0)];
        CCMoveBy *bagSprite2MoveBy=[CCMoveBy actionWithDuration:6.0f position:ccp(BGIMG_WIDTH,0)];
        CCCallBlock *bagSprite1Finish=[CCCallBlock actionWithBlock:^(void){[self actionFinishedWithSprite:bagSprite1];}];
        CCCallBlock *bagSprite2Finish=[CCCallBlock actionWithBlock:^(void){[self actionFinishedWithSprite:bagSprite2];}];
        
        [bagSprite1 runAction:[CCSequence actions:bagSprite1MoveBy,bagSprite1Finish,nil]];
        [bagSprite2 runAction:[CCSequence actions:bagSprite2MoveBy,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 actionFinishedWithSprite:theSprite];}];
        [theSprite runAction:[CCSequence actions:bagSpriteMoveBy,bagSpriteFinish,nil]];
    }
}


@end

运行结果:

cocos2d(背景图片循环滚动)_第1张图片

cocos2d(背景图片循环滚动)_第2张图片








转载于:https://www.cnblogs.com/lixingle/p/3707694.html

你可能感兴趣的:(cocos2d(背景图片循环滚动))