Cocos2d-x -- 如何让背景从上到下滚动

1. 首先,声明一个2个大小的sprite数组

class GameScreen : public cocos2d::Layer
{
public:
    ...
    cocos2d::Sprite *backgroundSpriteArray[2];
};


2. 完成初始化,1张图片用于当前显示,另1张用于滚动到下一张

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


4. 实现update方法

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

 

posted @ 2015-08-27 17:14  Master HaKu  阅读(567)  评论(0编辑  收藏  举报