横版游戏背景的移动

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值