Cocos2D-x游戏开发之十:背景无限滚动

        今天研究了一下Coco2D-x的背景无限滚动,其实是学习别人的demo,不过自己最终还是折腾出来了,其实还是比较简单了,就是背景不停地移动然后两张图片交替的贴上去。

其精髓之处就是不断地更新背景然后在每一帧里调整两张背景的\X锚点,然后就会给人一种主角再向前奔跑的感觉。核心代码如下:

bool TollgateScene::init()
{
bool bRet = false;
do 
{
CC_BREAK_IF(! CCLayer::init());
CCSize size= CCDirector::sharedDirector()->getWinSize();
CCSprite* sprite = CCSprite::create("sprite.png");
//sprite->setPosition(ccp(size.width/2, size.height/2));
m_player = Player::createWithLayer(this);
m_player->BlindSprite(sprite);
this->addChild(m_player,2);
m_player->setPosition(ccp(size.width/2,size.height/2));
InitBG();
this->scheduleUpdate();
//schedule(schedule_selector(TollgateScene::update),1.0f); 
} while (0);
return true;
}




int TollgateScene::InitBG(void)
{
m_sprite1 =CCSprite::create("tollgateBG.jpg");
m_sprite2=CCSprite::create("tollgateBG.jpg");
CCSize size= CCDirector::sharedDirector()->getWinSize();
m_sprite1->setPosition(ccp(size.width/2,size.height/2));
m_sprite2->setPosition(ccp(size.width+size.width/2,size.height/2));
m_sprite2->setFlipX(true);
this->addChild(m_sprite1,1);
this->addChild(m_sprite2,1);
return 0;
}
void TollgateScene::update(float delta)
{
int X1 = m_sprite1->getPositionX();
int X2 = m_sprite2->getPositionX();
int speed=2;
X1-=speed;
X2-=speed;
CCSize size = m_sprite1->getContentSize();
if (X1<-size.width/2)
{
X2 = size.width/2;
X1=size.width/2+size.width;
}
if (X2<-size.width/2)
{
X1 = size.width/2;
X2=size.width/2+size.width;
}
m_sprite1->setPositionX(X1);
m_sprite2->setPositionX(X2);
}


Cocos2D-x游戏开发之十:背景无限滚动_第1张图片

你可能感兴趣的:(Cocos2D-x开发之道,Windows)