天天看點

橫版遊戲背景的移動

init

//加背景

   CCSprite * repeat;

    _background = CCSprite::createWithSpriteFrameName("background.png");

    _background->setAnchorPoint(ccp(0,0));

    gameBatchNode->addChild(_background, 0);

    repeat = CCSprite::createWithSpriteFrameName("background.png");

    repeat->setAnchorPoint(ccp(0,0));

    repeat->setPosition(ccp(repeat->getContentSize().width - 1, 0));

    _background->addChild(repeat, 0);

    repeat = CCSprite::createWithSpriteFrameName("background.png");

    repeat->setAnchorPoint(ccp(0,0));

    repeat->setPosition(ccp(2 * (repeat->getContentSize().width - 1), 0));

    _background->addChild(repeat, 0);

//設定路燈  前景

   _foreground = CCSprite::createWithSpriteFrameName("lamp.png");  

   _foreground->setAnchorPoint(ccp(0,0));  

   gameBatchNode->addChild(_foreground, 0);  

   repeat = CCSprite::createWithSpriteFrameName("lamp.png");  

   repeat->setAnchorPoint(ccp(0,0));  

   repeat->setPosition(ccp(repeat->getContentSize().width * 4, 0));  

   _foreground->addChild(repeat, 0);  

   repeat = CCSprite::createWithSpriteFrameName("lamp.png");  

   repeat->setAnchorPoint(ccp(0,0));  

   repeat->setPosition(ccp(repeat->getContentSize().width * 8, 0));  

   _foreground->addChild(repeat, 0);

update

//移動背景 

      _background->setPositionX(_background->getPosition().x - 5);  

      float diffx;  

      //移完一個寬度時,重新把位置設定為接近0的位置  

//getContentSize獲得精靈矩形的寬高  

      if (_background->getPositionX() < -_background->getContentSize().width) {  

          diffx = fabs(_background->getPositionX()) - _background->getContentSize().width;  

    //移動場景  每移動一個機關的背景寬度,重置一次

          _background->setPositionX(-diffx);  //相當于前移一個背景寬度(補充微小偏移)

      } 

    //移動前景

 _foreground->setPositionX(_foreground->getPosition().x - 10);  

if (_foreground->getPositionX() < -_foreground->getContentSize().width * 4) {  

    diffx = fabs(_foreground->getPositionX()) - _foreground->getContentSize().width * 4;  

    _foreground->setPositionX(-diffx);  

}