1. 首先,声明一个2个大小的sprite数组
class GameScreen : public cocos2d::Layer{public: ... cocos2d::Sprite *backgroundSpriteArray[2];};
bool GameScreen::init(){ // // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Point origin = Director::getInstance()->getVisibleOrigin(); ... for (int i = 0; i < 2; i ++) { backgroundSpriteArray[i] = Sprite::create("GameScreen/Game_Screen_Background.png"); backgroundSpriteArray[i]->setPosition(Point((visibleSize.width / 2), (-1 * visibleSize.height * i) + (visibleSize.height / 2))); this->addChild(backgroundSpriteArray[i], -2); } ...}
3. 声明update方法表示每帧的更新
class GameScreen : public cocos2d::Layer{public: ... void update(float dt);};
void GameScreen::update(float dt){ Size visibleSize = Director::getInstance()->getVisibleSize(); Point origin = Director::getInstance()->getVisibleOrigin(); for (int i = 0; i < 2; i ++) { if (backgroundSpriteArray[i]->getPosition().y >= visibleSize.height + (visibleSize.height / 2) -1) { backgroundSpriteArray[i]->setPosition(Point((visibleSize.width / 2) + origin.x, (-1 * visibleSize.height) + (visibleSize.height / 2))); } } for (int i = 0; i < 2; i ++) { backgroundSpriteArray[i]->setPosition(Point(backgroundSpriteArray[i]->getPosition().x, backgroundSpriteArray[i]->getPosition().y + (0.75 * visibleSize.height * dt))); } ...}
5. 触发默认的update方法
bool GameScreen::init(){ ... this->scheduleUpdate(); ...}