横版游戏背景的移动

本文介绍如何使用Cocos2d-x游戏引擎通过创建多个背景精灵并重复添加到父节点来实现无限循环的背景滚动效果。同时,文中还展示了如何设置路灯等前景元素,并通过更新函数控制背景及前景的平滑移动,确保游戏画面的连贯性和视觉效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值