在跑酷游戏(天天酷跑)或者射击游戏(打飞机)中都有背景循环移动的机制。网上也有很多的实现方法,我这里先直接用代码反映出来:
首先申明的是我这个是做的横版向左移动:
- /*
- HelloWorldScene.h
- */
- #ifndef__HELLOWORLD_SCENE_H__
- #define__HELLOWORLD_SCENE_H__
- #include"cocos2d.h"
- #defineMAP_1_Tag1//宏定义两个Map的Tag
- #defineMAP_2_Tag2
- classHelloWorld:publiccocos2d::cclayer
- {
- private:
- voidupdate(floattime);
- virtualvoidonExit();
- public:
- virtualboolinit();
- staticcocos2d::CCScene*scene();
- CREATE_FUNC(HelloWorld);
- };
- #endif
- HelloWorldScene.cpp
- #include"HelloWorldScene.h"
- USING_NS_CC;
- CCScene*HelloWorld::scene()
- CCScene*scene=CCScene::create();
- HelloWorld*layer=HelloWorld::create();
- scene->addChild(layer);
- returnscene;
- }
- boolHelloWorld::init()
- if(!cclayer::init())
- returnfalse;
- }
- CCSizevisibleSize=CCDirector::sharedDirector()->getVisibleSize();
- CCPointorigin=CCDirector::sharedDirector()->getVisibleOrigin();
- CCSprite*map1=CCSprite::create("HelloWorld.png");
- CCSprite*map2=CCSprite::create("HelloWorld.png");
- map1->setPosition(ccp(map1->getContentSize().width/2+origin.x,map1->getContentSize().height/2+origin.y));
- map2->setPosition(ccp(map2->getContentSize().width/2+origin.x+map2->getContentSize().width,map2->getContentSize().height/2+origin.y));
- this->addChild(map1,MAP_1_Tag);
- this->addChild(map2,MAP_2_Tag);
- this->scheduleUpdate();
- true;
- voidHelloWorld::update(floattime)
- {
- CCSizevisibleSize=CCDirector::sharedDirector()->getVisibleSize();
- CCPointorigin=CCDirector::sharedDirector()->getVisibleOrigin();
- CCSprite*temmap1=(CCSprite*)this->getChildByTag(MAP_1_Tag);
- CCSprite*temmap2=(CCSprite*)this->getChildByTag(MAP_2_Tag);
- temmap1->setPositionX(temmap1->getPositionX()-5);
- temmap2->setPositionX(temmap2->getPositionX()-5);
- if(temmap1->getPositionX()+temmap1->getContentSize().width/2<=origin.x)
- floatoffset=temmap1->getPositionX()+temmap1->getContentSize().width/2-origin.x;
- temmap1->setPosition(ccp(temmap1->getContentSize().width/2+origin.x+visibleSize.width+offset,visibleSize.height/2+origin.y));
- if(temmap2->getPositionX()+temmap2->getContentSize().width/2<=origin.x)
- floatoffset=temmap2->getPositionX()+temmap2->getContentSize().width/2-origin.x;
- temmap2->setPosition(ccp(temmap2->getContentSize().width/2+origin.x+visibleSize.width+offset,153); background-color:inherit; font-weight:bold">voidHelloWorld::onExit()
- this->unscheduleUpdate();
- cclayer::onExit();
- }