首页 > 代码库 > Cocos2d-X循环背景效果

Cocos2d-X循环背景效果

准备一张两边可循环连接的图,使用下面代码即可实现~

HelloWorld::bd(0, 0, 98);HelloWorld::bd(0, 2130, 99);this->schedule(schedule_selector(HelloWorld::move));
void HelloWorld::bd(float num, int w, int tag){    CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();    CCSize size = CCDirector::sharedDirector()->getWinSize();    float x = size.width, y = size.height + origin.y;    CCSprite *background = CCSprite::create("bg.png");    background->setAnchorPoint(CCPoint(0, 0.5));    background->setPosition(CCPoint(background->getContentSize().width*num + w, y / 2));    this->addChild(background, tag, tag);}void HelloWorld::move(float time){    CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();    CCSize size = CCDirector::sharedDirector()->getWinSize();    float x = size.width, y = size.height + origin.y;    CCNode *bg1 = CCNode::getChildByTag(99);    CCSprite *sp1 = (CCSprite*)bg1;    CCNode *bg2 = CCNode::getChildByTag(98);    CCSprite *sp2 = (CCSprite*)bg2;    sp1->setPosition(CCPoint(sp1->getPositionX() - 0.5, sp1->getPositionY()));    sp2->setPosition(CCPoint(sp2->getPositionX() - 0.5, sp2->getPositionY()));    if (sp1->getPositionX() <= -sp1->getContentSize().width) sp1->setPosition(CCPoint(sp1->getContentSize().width, y / 2));    if (sp2->getPositionX() <= -sp2->getContentSize().width) sp2->setPosition(CCPoint(sp2->getContentSize().width, y / 2));}

 

Cocos2d-X循环背景效果