横版游戏背景的移动

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);  
}  


你可能感兴趣的:(cocos2d-x,学习)