直接上代码
在初始化方法中添加图片:
bool BackGroundLayer::init() { frameCache=CCSpriteFrameCache::sharedSpriteFrameCache(); CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize(); bgCell1=CCSprite::createWithSpriteFrame(frameCache->spriteFrameByName("bgCell.png")); bgSprintArr = CCArray::create(); bgSprintArr->retain(); bgSignArr=CCArray::create(); bgSignArr->retain(); CCSize sprintSize = bgCell1->getContentSize(); bgCell1->setAnchorPoint(ccp(0,0)); bgCell1->setPosition(ccp(0,0)); this->addChild(bgCell1); bgSprintArr->addObject(bgCell1); int flipCount=visibleSize.width/sprintSize.width+1;//多加一张图片用来滚动替换 for(int i=0;i<flipCount;i++) { bgCell2 = CCSprite::createWithSpriteFrame(frameCache->spriteFrameByName("bgCell.png")); bgCell2->setAnchorPoint(ccp(0,0)); bgCell2->setPosition(ccp(sprintSize.width*(i+1)-(1+i),0)); if(i%2==0) //偶数 { bgCell2->setFlipX(true); } this->addChild(bgCell2); bgSprintArr->addObject(bgCell2); } return true; }
在界面刷新方法里处理:
void RunBackGroundLayer::rollBg(float delta)
{
//CCSize mapSize = bgCell1->getContentSize();
//本次需要滚动的像素数
float moveX =delta/(1.0/60.0);
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
CCObject* obj=NULL;
CCSprite* bgCellTmp=NULL;
CCSize sprintSize = bgCell1->getContentSize();
//滚动和切换背景图片
CCARRAY_FOREACH(bgSprintArr,obj){
bgCellTmp=(CCSprite*)obj;
float moveXTo = bgCellTmp->getPositionX()-moveX;
bgCellTmp->setPositionX(moveXTo);
if(bgCellTmp->getPositionX()<-sprintSize.width)
{
bgCellTmp->setPositionX((bgSprintArr->count()-1)*sprintSize.width-(bgSprintArr->count()+1));
if(bgSprintArr->count()%2!=0)
{
if(bgCellTmp->isFlipX())
{
bgCellTmp->setFlipX(false);
}
else
{
bgCellTmp->setFlipX(true);
}
}
}
}
}
完美实现无缝拼接滚动.