cocos2dx 背景用小尺寸图片滚动填充的方法

时间:2023-03-08 20:06:22
cocos2dx 背景用小尺寸图片滚动填充的方法

直接上代码

在初始化方法中添加图片:

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(,));
bgCell1->setPosition(ccp(,));
this->addChild(bgCell1);
bgSprintArr->addObject(bgCell1); int flipCount=visibleSize.width/sprintSize.width+;//多加一张图片用来滚动替换 for(int i=;i<flipCount;i++)
{
bgCell2 = CCSprite::createWithSpriteFrame(frameCache->spriteFrameByName("bgCell.png"));
bgCell2->setAnchorPoint(ccp(,));
bgCell2->setPosition(ccp(sprintSize.width*(i+)-(+i),));
if(i%==) //偶数
{
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);
}
}
}
} }

完美实现无缝拼接滚动.