代码如下:
class SprBg :public cocos2d::CCLayer
{
public:
//初始化
bool initBackground();
//每一帧调用一次,更新位置
void update(float dt);
//静态方法来产生对象
static SprBg* createBackground();
private:
};
bool SprBg::initBackground()
{
CCTexture2D* texture = CCTextureCache::sharedTextureCache()->addImage(
"F:\\cocos2d-x-2.2\\projects\\flyshow\\Resources\\HelloWorld.png");
CCSprite *bg = CCSprite::createWithTexture(texture);
CCSprite *bg_re = CCSprite::createWithTexture(texture);
if(bg && bg_re)
{
bg->setAnchorPoint(CCPointZero);
bg_re->setAnchorPoint(CCPointZero);
this->m_pFar = bg;
this->m_pFarRe = bg_re;
//增加标签方便以后调用
this->addChild(bg,-10,TAG_BG_FAR_LAYER);
this->addChild(bg_re,-9,TAG_BG_FAR_LAYER);
bg->setPosition(ccp(0,0));
bg_re->setPosition(ccp(BG_WIDTH ,0));
this->fFarVelocity = 150;
//变为智能对象
this->autorelease();
this->scheduleUpdate();
return true;
}
return false;
}
调用autorelease()后对象变成智能对象。
调用scheduleUpdate()后启动update定时器,每一帧调用一次重载的update函数。
void SprBg::update(float dt)
{
m_pFar->setPositionX(m_pFar->getPositionX() - fFarVelocity*dt);
if (m_pFar->getPositionX() < -1*BG_WIDTH)
{
}
m_pFarRe->setPositionX(m_pFarRe->getPositionX() - fFarVelocity*dt);
if (m_pFarRe->getPositionX() < -1*BG_WIDTH)
{
}
}
这里是滚动背景的主要逻辑。取出当前位置,计算下一帧应该出现的位置后更新。如果超出了可视范围就往后调整。其中dt是上一次update函数调用到这一次update函数调用的间隔时间。
SprBg* SprBg::createBackground()
{
SprBg* pBg = new SprBg();
if(pBg && pBg->initBackground())
return pBg;
}
为了统一cocos2d-x生成对象的风格,这里把声明对象和
初始化封装在静态函数里面。
效果如下